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

双指针法

class Solution {
    public int removeDuplicates(int[] nums) {

        /**
         * 同《80. 删除有序数组中的重复项II》
         */
        if (nums.length == 1){
            return 1;
        }
        
        int length = 1;

        for (int i = 1; i < nums.length; i++) {

            if (nums[i] != nums[length - 1]){
                
                nums[length] = nums[i];
                length++;
            }
        }

        return length;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

优化1——避免重复的赋值

class Solution {
    public int removeDuplicates(int[] nums) {

        if (nums.length == 0){
            return 0;
        }

        /**
         * 定义两个指针,一前一后,相差为1
         * 当遇到相等的元素时,left不动,right继续向前,直到找到一个不同的元素
         * 然后让right位置的元素覆盖left + 1位置,同时left加1
         * 如果两个位置只相差1,且不相等,则同时向前移动,不用覆盖
         */
        int left = 0;
        int right = 1;

        while (right < nums.length) {

            if (nums[left] == nums[right]){
                right++;
            }
            else if (right - 1 == left){

                left++;
                right++;
            }
            else {

                nums[left + 1] = nums[right];
                left++;
                right++;
            }
        }

        return left + 1;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/

posted @ 2021-11-23 15:58  振袖秋枫问红叶  阅读(29)  评论(0)    收藏  举报