Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Donot allocate extra space for another array, you must do this by modifying the input arrayin-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],
Your functionshouldreturnlength = 2, withthefirsttwoelementsofnumsbeing 1 and 2 respectively.
Itdoesn'tmatterwhatyouleavebeyondthereturnedlength.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your functionshouldreturnlength = 5, withthefirstfiveelementsofnumsbeingmodifiedto 0, 1, 2, 3, and 4 respectively.
Itdoesn'tmatterwhatvaluesaresetbeyondthereturnedlength.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input arrayis passed inbyreference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.// using the length returned by your function, it prints the first len elements.for (int i = 0; i < len; i++) {
print(nums[i]);
}
代码
class Solution {
publicintremoveDuplicates(int[] nums) {
int len = nums.length;
int reLen = 0 ;
int temp = Integer.MIN_VALUE;
if(len!=0){
if(nums[0]==temp)
{
temp = temp+1;
}
}
for(int i = 0 ;i<len;i++)
{
int num = nums[i];
if(temp==num)
{
continue;
}
else
{
nums[reLen++] = num;
}
temp = num;
}
return reLen;
}
}