LeetCode,leetcodeoj
題目連結: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].
這道題的要求是在有序數組中重複資料刪除元素,使每個數字出現且只出現1次,並返回數組的新的長度。要求:不允許申請額外空間,即要求恒定的空間複雜度。
這道題的思路就是採用兩個指標l和r,l記錄不重複元素的位置,r從l的下一個開始遍曆數組,如果r位置的數字等於l位置的數字,說明該數字重複出現,不予處理;如果r位置的數字不等於l位置的數字,說明該數字沒有重複,需要放到l的下一位置,並使l加1。
時間複雜度:O(n)
空間複雜度:O(1)
1 class Solution 2 { 3 public: 4 int removeDuplicates(int A[], int n) 5 { 6 if(n == 0) 7 return 0; 8 9 int l = 0;10 for(int r = 1; r < n; ++ r)11 if(A[r] != A[l])12 A[++ l] = A[r];13 return l + 1;14 }15 };
轉載請說明出處:LeetCode --- 26. Remove Duplicates from Sorted Array