zoukankan      html  css  js  c++  java
  • 26.Remove Deplicates from Sorted Array

    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 nums = [1,1,2],

    Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

    算法:

    因为数组已经有序,我们可以维持两个指针i 和 j, 只要nums[i] == nums[j], 就增加j 来跳出循环。

    当遇到nums[j] != nums[i], 查重循环结束, 我们必须把nums[j] 的值复制给nums[i+1】,i 然后增加。

    重复这一过程直到j 到达数组尾部。

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

      

  • 相关阅读:
    bzoj3832
    bzoj2117
    bzoj1095
    BZOJ 4247: 挂饰 题解
    1296: [SCOI2009]粉刷匠
    3163: [Heoi2013]Eden的新背包问题
    2287: 【POJ Challenge】消失之物
    1334: [Baltic2008]Elect
    2748: [HAOI2012]音量调节
    1606: [Usaco2008 Dec]Hay For Sale 购买干草
  • 原文地址:https://www.cnblogs.com/dreamafar/p/7231782.html
Copyright © 2011-2022 走看看