Google+ Followers

Sunday, December 30, 2012

[LeetCode] Remove Duplicates from Sorted Array 解题报告


Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
» Solve this problem

[解题思路]
二指针问题。一前一后扫描。


[Code]
1:    int removeDuplicates(int A[], int n) {  
2:      // Start typing your C/C++ solution below  
3:      // DO NOT write int main() function  
4:      int pre, cur;  
5:      pre = 1; cur = 1;  
6:      if(n <=1) return n;  
7:      while(cur<n)  
8:      {  
9:        if(A[cur] == A[cur-1])  
10:        {  
11:          cur++;  
12:          continue;  
13:        }  
14:        A[pre] = A[cur];  
15:        pre++;  
16:        cur++;  
17:      }  
18:      return pre;  
19:    }  


Updated. 3/9/2013
1:    int removeDuplicates(int A[], int n) {  
2:      if(n ==0) return 0;  
3:      int index = 0;  
4:      for(int i =0;i<n; i++)  
5:      {  
6:        if(A[index] == A[i])  
7:        {  
8:          continue;  
9:        }  
10:        index++;  
11:        A[index] = A[i];  
12:      }  
13:      return index+1;  
14:    }  


Post a Comment