美文网首页
P5-删除排序数组中的重复项

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

作者: YonchanLew | 来源:发表于2021-05-08 23:13 被阅读0次
//删除排序数组中的重复项
/*
 * 一个有序数组nums,原地删除重复出现的元素,使每个元素只出现一次,返回删除后数组的新长度
 * 不能使用额外的数组空间,必须在原地修改输入数组并在使用O(1)额外空间的条件下完成
 * */
public class P5 {
    public static void main(String[] args) {
        System.out.println(removeDuplicates(new int[]{0, 1, 2, 2, 3, 3, 4}));
    }

    //双指针算法
    public static int removeDuplicates(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }

        int i = 0;
        for (int j = 1; j < nums.length; j++) {
            if (nums[j] != nums[i]) {
                i++;
                nums[i] = nums[j];
            }
        }

        return i + 1;
    }
}

相关文章

网友评论

      本文标题:P5-删除排序数组中的重复项

      本文链接:https://www.haomeiwen.com/subject/hothdltx.html