快慢指针算法-数组去重

通过快慢指针方式对数组进行去重

    public static void main(String[] args) {
        int[] a = {1, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 9, 10, 11};
        int startI = 0;
        int endI = 1;

        while (startI < endI && endI < a.length) {
            if (a[startI] == a[endI]) {
                endI++;
                continue;
            }
            startI++;
            a[startI] = a[endI];
            endI++;
        }
        System.out.println(JSON.toJSONString(a));
    }

输出结果:

[1,2,3,4,5,6,7,8,9,10,11,6,7,7,7,7,8,9,10,11]

 

另一种解法:通过把重复元素移动到结尾

    public static int removeDuplicates(int[] nums) {
        if (nums.length == 0 || nums.length == 1) {
            return nums.length;
        }
        int start = 0;
        int end = nums.length - 1;
        while (start < end && (start + 1) < nums.length) {
            if (nums[start] == nums[start + 1]) {
                int temp = nums[start + 1];
                for (int i = start + 1; i < end; i++) {
                    nums[i] = nums[i + 1];
                }
                nums[end] = temp;
                end--;
            }else {
                start++;
            }
        }
        return start;
    }

 

posted @ 2020-07-14 00:03  使用D  阅读(415)  评论(0编辑  收藏  举报