LeetCode:删除排序数组中的重复项 (Remove Duplicates from Sorted Array)

Posted wymc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:删除排序数组中的重复项 (Remove Duplicates from Sorted Array)相关的知识,希望对你有一定的参考价值。

public class RemoveDuplicates {
    /**
     * 修改数组,使数组有序不重复。超出长度不考虑。
     * @param 排序数组
     * @return 数组不重复数的个数
     */
    public int removeDuplicates(int[] nums) {
        // 需要修改的元素的索引,从1开始
        int index = 1;
        // 遍历数组,次数是长度-1
        for (int i = 0; i < nums.length - 1; i++) {
            // 对相邻数进行异或,相同数异或值为0
            if ((nums[i] ^ nums[i + 1]) != 0) {
                // 两个数不同时,将后续数放到索引位置,同时索引自增
                nums[index++] = nums[i + 1];
            }
        }
        //直接返回索引,因为索引在改变元素后自增,等于有序数组长度
        return index;
    }
}

 

以上是关于LeetCode:删除排序数组中的重复项 (Remove Duplicates from Sorted Array)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode:删除排序数组中的重复项||80

leetcode26 删除排序数组中的重复项(Easy)

LeetCode 第26题 删除排序数组中的重复项

[leetcode] 26. 删除排序数组中的重复项

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

Leetcode-删除排序数组中的重复项