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.
这个题挺简单的,但是题干中的 two elements of nums being 1
and 2
respectively 有点蛋疼。并不清楚这个是要干什么。 这样,一遍循环即可完成,用一个int 记录不重复长度,一个临时变量保存当前值,如果数组的下一位比它大的话那计数加一,更新当前数。
package leetcode;
public class RemoveDuplicate {
public static void main(String[] args) {
RemoveDuplicate r = new RemoveDuplicate();
int nums[]={1,1,2,2,4,6,8,8,8,8,8,10};
System.out.println(r.removeDuplicates(nums));
}
//扫一遍,碰到比他大的计数再加一,然后 更新当前的值
public int removeDuplicates(int[] nums) {
if(nums.length==0){
return 0;
}
if(nums.length == 1){
return nums[0];
}
int count=1;
int cur=nums[0];
for(int i=1;i<nums.length;i++){
if(nums[i]>cur){
count++;
cur=nums[i];
nums[count-1] = cur;
}
}
for(int i=0;i<nums.length;i++){
System.out.print(" "+nums[i]);
}
return count;
}
}