(C++練習) 26. Remove Duplicates from Sorted Array

題目 :

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.

大意 :

給一個排列好的 array, 移除重複的元素, 而且不許另外分配額外的 array.

 1 class Solution {
 2 public:
 3     int removeDuplicates(vector<int>& nums) {
 4         if (nums.empty()) return 0;
 5         int index = 0;
 6         for (int i = 0; i < nums.size(); i++){
 7             if (nums[index] != nums[i]){
 8                 nums[++index] = nums[i];
 9             }
10         }
11         return index + 1;
12     }
13 };

猜你喜欢

转载自www.cnblogs.com/ollie-lin/p/10434688.html
今日推荐