Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2], Your function should return length =2
, with the first two elements ofnums
being1
and2
respectively. It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4], Your function should return length =5
, with the first five elements ofnums
being modified to0
,1
,2
,3
, and4
respectively. It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy) int len = removeDuplicates(nums); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); }
這道題要我們從有序陣列中去除重複項,和之前那道 Remove Duplicates from Sorted List 的題很類似,但是要簡單一些,因為畢竟陣列的值可以通過下標直接訪問,而連結串列不行。那麼這道題的解題思路是,我們使用快慢指標來記錄遍歷的座標,最開始時兩個指標都指向第一個數字,如果兩個指標指的數字相同,則快指標向前走一步,如果不同,則兩個指標都向前走一步,這樣當快指標走完整個陣列後,慢指標當前的座標加1就是陣列中不同數字的個數,程式碼如下:
解法一:
class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.empty()) return 0; int pre = 0, cur = 0, n = nums.size(); while (cur < n) { if (nums[pre] == nums[cur]) ++cur; else nums[++pre] = nums[cur++]; } return pre + 1; } };
我們也可以用for迴圈來寫,這裡的j就是上面解法中的pre,i就是cur,所以本質上都是一樣的,參見程式碼如下:
解法二:
class Solution { public: int removeDuplicates(vector<int>& nums) { if (nums.empty()) return 0; int j = 0, n = nums.size(); for (int i = 0; i < n; ++i) { if (nums[i] != nums[j]) nums[++j] = nums[i]; } return j + 1; } };
類似題目:
Remove Duplicates from Sorted List
Remove Duplicates from Sorted List II
Remove Duplicates from Sorted Array II
類似題目:
https://leetcode.com/problems/remove-duplicates-from-sorted-array/