Poison

26. Remove Duplicates from Sorted Array

Two Pointers
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int removeDuplicates(int[] nums) {
int i = 0; // 去重子数组的最后一个元素索引
for (int j = 1; j < nums.length; j++) {
if (nums[j] != nums[i]) {
nums[++i] = nums[j];
}
}

return i + 1; // 返回去重子数组的长度
}
}
Two Pointers
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int removeDuplicates(int[] nums) {
int i = 0; // 指向即将写入数据的索引
for (int num : nums) {
if (i == 0 || num != nums[i - 1]) {
nums[i++] = num;
}
}

return i; // 返回去重子数组的长度
}
}
Reference

26. Remove Duplicates from Sorted Array