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

      

  • 相关阅读:
    vim技巧2
    vim技巧1
    网站压力测试工具
    CentOS mysql安装
    破解root
    渐进式性能监测案例
    网络监测介绍
    I/O检测介绍
    虚拟内存介绍
    @Slf4j
  • 原文地址:https://www.cnblogs.com/dreamafar/p/7231782.html
Copyright © 2011-2022 走看看