26.删除有序数组中的重复项
自己写的,双指针,用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 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步