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.
Example 1:
Given nums = [1,1,2], Your function should return length =2
, with the first two elements ofnums
being1
and2
respectively. It doesn't matter what you leave beyond the returned length.
You don't need to keep the original order of the integers.
思路:双指针,每次把i != j的值,赋值到++i的位子,最后返回i+1,因为是个数;
class Solution {
public int removeDuplicates(int[] nums) {
if(nums == null || nums.length == 0) {
return 0;
}
int i = 0; int j = 0;
while(j < nums.length) {
if(nums[i] == nums[j]) {
j++;
} else {
nums[++i] = nums[j];
j++;
}
}
return i + 1;
}
}