leetcode 26. Remove duplicates in sorted array

Given a sorted array, you need to remove duplicate elements in place so that each element occurs only once, and return the new length of the removed array.

Instead of using extra array space, you have to modify the input array in- place and do it with O(1) extra space.

Example 1:

Given an array nums = [1,1,2],

The function should return a new length of 2, with the first two elements of the original array nums modified to 1, 2.

You don't need to consider elements in the array beyond the new length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

The function should return a new length of 5, and the first five elements of the original array nums are modified to 0, 1, 2, 3, 4.

You don't need to consider elements in the array beyond the new length.

illustrate:

Why is the returned value an integer, but the output answer is an array?

Note that the input array is passed "by reference", which means that modifications to the input array within the function are visible to the caller.

You can imagine the internal operation as follows:

// nums are passed "by reference". That is, do not make any copies of the actual parameters
int len = removeDuplicates(nums);

// Modifications to the input array in the function are visible to the caller.
// Based on the length returned by your function, it will print out all elements in the array within that length.
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

1 class Solution {
2 public:
3     int removeDuplicates(vector<int>& nums) {
4         auto index = unique(nums.begin(), nums.end());
5         nums.erase(index, nums.end());
6         int ans = nums.size();
7         return ans;
8     }
9 };

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324880945&siteId=291194637