題目 :
- Given a sorted array nums, remove the duplicates in-place https://en.wikipedia.org/wiki/In-place_algorithm 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 https://en.wikipedia.org/wiki/In-place_algorithm with O(1) extra memory.
大意 :
給一個排列好的 array, 移除重複的元素, 而且不許另外分配額外的 array.
- class Solution {
- public:
- int removeDuplicates(vector& nums) {
- if (nums.empty()) return 0;
- int index = 0;
- for (int i = 0; i < nums.size(); i++){
- if (nums[index] != nums[i]){
- nums[++index] = nums[i];
- }
- }
- return index + 1;
- }
- };
来源: http://www.bubuko.com/infodetail-2967986.html