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].

 1 class Solution {
 2 public:
 3     int removeDuplicates(int A[], int n) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int tail  = 0;
 7         int rtn = n;
 8         for(int i=1; i<n; i++){
 9             while(i<n && A[i] == A[tail]){
10                 i++;
11                 rtn--;
12             }
13             A[++tail] = A[i];
14         }
15         return rtn;
16     }
17 };

Run Status: Accepted!
Program Runtime: 68 milli secs

Progress: 160/160 test cases passed.
!红色部分判定一开始没有加上,导致部分用例没能通过。
[0,0,0,1,2,2,4,4]        输出:[0,1,2]
[-3,-3,-2,-1,-1,0,0,0,0,0]      输出:[-3,-2,-1]

相关文章:

  • 2021-10-23
  • 2022-01-26
  • 2021-12-09
猜你喜欢
  • 2021-06-08
  • 2021-10-12
  • 2021-06-22
相关资源
相似解决方案