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.
给定一个排序array,移除重复的部分。返回新的length。
算法分析
- 选取两个索引,i,j。j表示原始数组索引,遍历所有的值;i表示去除重复值后的索引。
- j在前,如果当前位置处值不与i位置处的值相同,就将nums[i+1]=nums[j]
代码
public class Solution {
public int removeDuplicates(int[] nums) {
int i = 0;
//如果i、j位置处两个值相等,j++,直到不相等为止,将nums[j]赋给nums[i+1]
for (int j = 1; j < nums.length; j ++) {
if (nums[i] != nums[j]) {//只要两个值不等,就将当前j位置的值放到i+1位置处
i ++;
nums[i] = nums[j];
}
}
return i + 1;
}
}