美文网首页
LeetCode每日一题:remove duplicates f

LeetCode每日一题:remove duplicates f

作者: yoshino | 来源:发表于2017-05-18 16:02 被阅读8次

    问题描述

    Given a sorted array, 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 in place with constant memory.
    For example,
    Given input array A =[1,1,2],
    Your function should return length =2, and A is now[1,2].

    问题分析

    剔除重复元素,不能使用额外的空间和新的数组,用count计数,遇到不重复的加入原先数组进行覆盖即可

    代码实现

    public int removeDuplicates(int[] A) {
            if (A.length == 0 || A.length == 1) return A.length;
            int count = 1;
            for (int i = 1; i < A.length; i++) {
                if (A[i] != A[i - 1]) {
                    A[count] = A[i];
                    count++;
                }
            }
            return count;
        }
    

    相关文章

      网友评论

          本文标题:LeetCode每日一题:remove duplicates f

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