LeeCode from 0 ——26. Remove Duplicates from Sorted Array

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.

解题思路:

1)判断数组长度,若为0或者1则直接返回,否则进入2);

2)将数组中每个元素nums[j]比较,若与nums[j]中数字不同,则将j加1,此数字存入nums[j]中,再将此时nums[j]中数字继续与数组元素比较,直至数组结束。

代码如下:

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n=nums.size();
int j=0;
if(n==0)
return n;
else if(n==1)
return n;
else{
int i=1;
while(i<n){
if(nums[j]==nums[i])
i++;
else{
j++;
nums[j]=nums[i];
i++;
}
}
}
return j+1;
}
};

猜你喜欢

转载自www.cnblogs.com/ssml/p/9177879.html