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.
Subscribe to see which companies asked this question
移除数组中重复的数,要求在原数组上操作,常数的空间。
用两个指针,后一个指针指向的数与前一项比较,如果相等,则指针后移,如果不相等,则将这个数赋值给前一个指针所指的位置。
c++
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int num = 0 , front = 1 , last = 1 , size = nums.size() ;
if (size == 0 ) return 0 ;
if ( size == 1 ) return 1 ;
while ( last < size) {
if ( nums[last] != nums[last - 1] ) {
nums[front] = nums[last] ;
front ++ ;
}
last ++ ;
}
return front ;
}
};
java
public class Solution {
public int removeDuplicates(int[] nums) {
int num = 0 , front = 1 , last = 1 , size = nums.length ;
if (size == 0 ) return 0 ;
if ( size == 1 ) return 1 ;
while ( last < size) {
if ( nums[last] != nums[last - 1] ) {
nums[front] = nums[last] ;
front ++ ;
}
last ++ ;
}
return front ;
}
}