题目
思路1:双指针(只关心赋值)
class Solution {
public static int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
nums[i + 1] = nums[j];
i++;
}
}
return i + 1;
}
}
思路2(保持所有元素swap)
class Solution {
public static int removeDuplicates(int[] nums) {
int count = 0;
int fast = 1;
while (fast < nums.length) {
while (fast < nums.length && nums[fast] == nums[count]) {
fast++;
}
if (fast == nums.length) return count + 1;
swap(nums, ++count, fast);
fast++;
}
return count+1;
}
public static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
总结