Leetcode_26删除排序树组中的重复项

题目

在这里插入图片描述

思路1:双指针(只关心赋值)

class Solution {
    
    
    public static int removeDuplicates(int[] nums) {
    
    
        if (nums.length == 0) return 0;
        //i指针和j指针

        //j指针一直向后扫描
        //i指针作为慢指针更新不重复元素
        int i = 0;
        for (int j = 1; j < nums.length; j++) {
    
    
            if (nums[j] != nums[i]) {
    
    
                nums[i + 1] = nums[j];
                i++;
            }
        }
        return i + 1;
    }
}

思路2(保持所有元素swap)

//{0, 0, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 9}
class Solution {
    
    
    public static int removeDuplicates(int[] nums) {
    
    
        int count = 0;
        int fast = 1;
        while (fast < nums.length) {
    
    
            while (fast < nums.length && nums[fast] == nums[count]) {
    
    
                fast++;
            }

            if (fast == nums.length) return count + 1;
            swap(nums, ++count, fast);
            fast++;
        }
//        System.out.println(fast);
        return count+1;
    }

    public static void swap(int[] nums, int i, int j) {
    
    
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

总结

猜你喜欢

转载自blog.csdn.net/AC_872767407/article/details/114479307
今日推荐