您的位置:首页 > 其它

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

2012-12-31 11:44 447 查看
Given a sorted array, remove the duplicates in place such that each element appear only once[/i] 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:    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: