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.
給定一個(gè)排序array,移除重復(fù)的部分。返回新的length。
算法分析
- 選取兩個(gè)索引,i,j。j表示原始數(shù)組索引,遍歷所有的值;i表示去除重復(fù)值后的索引。
- j在前,如果當(dāng)前位置處值不與i位置處的值相同,就將nums[i+1]=nums[j]
代碼
public class Solution {
public int removeDuplicates(int[] nums) {
int i = 0;
//如果i、j位置處兩個(gè)值相等,j++,直到不相等為止,將nums[j]賦給nums[i+1]
for (int j = 1; j < nums.length; j ++) {
if (nums[i] != nums[j]) {//只要兩個(gè)值不等,就將當(dāng)前j位置的值放到i+1位置處
i ++;
nums[i] = nums[j];
}
}
return i + 1;
}
}