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.
EX:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length.
想法:
直接遍歷整個 array,若遇到不重複的元素就將它覆蓋到 array 前方。
完整程式碼:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) { return 0; }
int i = 0;
for (size_t j = 1; j < nums.size(); j++) {
if (nums.at(j) != nums.at(i)) {
nums.at(++i) = nums.at(j);
}
}
// return length
return i + 1;
}
};
沒有留言:
張貼留言