leetcode 26

时间:2023-03-08 16:47:19

26. Remove Duplicates from Sorted Array

Given a sorted array, 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 in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

对排好序的数列去重。返回不重复的数的个数n,并将其一次排列在原来数组的前n位。

代码如下:

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.empty())
{
return ;
}
int n = nums.size();
if(n == )
{
return ;
}
int sum = ;
int j = ;
for(int i = ; i < n; i++)
{
if(nums[j] != nums[i])
{
nums[j+] = nums[i];
sum++;
j++;
} }
return sum;
}
};