LeetCode 26: 从排序数组中删除重复项

题目

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
示例 1:
给定数组 nums = [1,1,2],
函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为 1, 2。
你不需要考虑数组中超出新长度后面的元素。
感觉题目有点迷惑人,这个题的思路不需要删除重复的数据,只需要换个位置就好,题目可以改成 获取排序数组中不同元素的个数

思路

这道题的解题思路是,我们使用快慢指针来记录遍历的坐标,最开始时两个指针都指向第一个数字,如果两个指针指的数字相同,则快指针向前走一步,如果不同,则两个指针都向前走一步,这样当快指针走完整个数组后,慢指针当前的坐标加1就是数组中不同数字的个数。

 public static int removeDuplicates1(int[] nums ) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int pre = 0, cur = 0, n = nums.length;
        while (cur < n) {
            if (nums[pre] == nums[cur]) {
                ++cur;
            }
            else {
                nums[++pre] = nums[cur];
                ++cur;
            }
        }
        return pre + 1;
    }

解法二:
也可以使用for循环来写,解法二的j就是解法一中的pre,i就是cur.

 public static int removeDuplicates(int[] nums){
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int back = 0;
        for (int front = 1; front < nums.length; front++) {
            if (nums[back] != nums[front]) {
                back++;
                nums[back] = nums[front];
            }
        }
        return back + 1;
    }

参考资料 leetcode26
https://leetcode.com/problems/remove-duplicates-from-sorted-array/

你可能感兴趣的:(LeetCode)