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;
    }
}

猜你喜欢

转载自www.cnblogs.com/wymc/p/10051166.html