Remove Duplicates from Sorted Array [LEETCODE]
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].
==============================================================================
Duplicates may appear more than two...
So consider input A = [1,1,1,1,2], we need a while loop , not only a if case.
And the while loop need to qiut when i<n.
1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) { 4 // Note: The Solution object is instantiated only once and is reused by each test case. 5 for(int i = 1; i < n; i++){ 6 while(i < n && A[i] == A[i - 1]){ 7 for(int j = i; j < n - 1; j++){ 8 A[j] = A[j + 1]; 9 } 10 n = n - 1; 11 } 12 } 13 return n; 14 15 } 16 };

浙公网安备 33010602011771号