自己写的,双指针,用tail指针指向不重复有序数组的末尾元素,用index指针进行遍历数组,遇到和末尾元素不一样的元素,放到tail+1的位置,然后tail指针加1
class Solution {
public static int removeDuplicates(int[] nums) {
int tail = 0;
int index = 0;
int max = nums.length;
while(index < max){
if(nums[index] != nums[tail]){
nums[tail+1] = nums[index];
tail ++;
}
index ++;
}
return tail+1; // 数组起始为0,所以+1
}
public static void swap(int[] nums, int a, int b){
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
}
}
官方题解:
思路一样,代码更好
class Solution {
public int removeDuplicates(int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
int fast = 1, slow = 1; // 快慢指针
while (fast < n) {
if (nums[fast] != nums[fast - 1]) { // 相邻的元素不同,即发现新元素
nums[slow] = nums[fast];
++slow;
}
++fast;
}
return slow;
}
}
标签:index,26,slow,删除,nums,int,fast,tail,数组
From: https://www.cnblogs.com/lmc7/p/18095560