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,移除重復(fù)的部分师痕。返回新的length痹升。
算法分析
- 選取兩個索引驮履,i酣难,j古拴。j表示原始數(shù)組索引厌衔,遍歷所有的值驻襟;i表示去除重復(fù)值后的索引夺艰。
- 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;
}
}