题目:
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 A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
大概意思就是去掉一个有序数组重复的元素。
我按照网上的答案运行了下,发现结果不对啊?下面是代码,求解惑
public class Solution {
public static int removeDuplicate(int[] nums){
if(nums.length == 0 || nums.length == 1) {
return nums.length;
}
int index=0, i=1;
while(i<nums.length) {
if(nums[index] == nums[i]) {
i++;
}else {
nums[++index] = nums[i];
i++;
}
}
return ++index;
}
public static void main(String[] args){
int[] nums = new int[]{1, 1, 2};
System.out.println("---------------");
int length = removeDuplicate(nums);
System.out.println(length);
System.out.println(Arrays.toString(nums));
}
}
运行结果为:
---------------
2
[1, 2, 2]
但是按照题目的要求,数组A不是应该变成[1,2]了么?求大神分析下吧,C币实在不多,求帮忙。