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;
    }
}
posted @ 2024-03-25 22:24  清澈的澈  阅读(2)  评论(0编辑  收藏  举报