2024-03-25 22:24阅读: 4评论: 0推荐: 0

26.删除有序数组中的重复项

image-20240325210407021

自己写的,双指针,用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;
}
}

本文作者:清澈的澈

本文链接:https://www.cnblogs.com/lmc7/p/18095560

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   清澈的澈  阅读(4)  评论(0编辑  收藏  举报
评论
收藏
关注
推荐
深色
回顶
收起
点击右上角即可分享
微信分享提示