zoukankan      html  css  js  c++  java
  • Lintcode521-Remove Duplicate Numbers in Array-Easy

    Description

    Given an array of integers, remove the duplicate numbers in it.

    You should:

    1. Do it in place in the array.
    2. Move the unique numbers to the front of the array.
    3. Return the total number of the unique numbers.
    Example 1:
    Input:
    nums = [1,3,1,4,4,2]
    Output:
    [1,3,4,2,?,?]
    4

    Challenge

    1. Do it in O(n) time complexity.
    2. Do it in O(nlogn) time without extra space.

    O(n) time, O(n) space

    思路2: 双指针法

    O(nlogn) time, O(1) extra space

    先对数组排序,再用快指针遍历整个数组,慢指针改变数组使其只包含非重复数字。

    注意:

    快指针放在for循环里。慢指针在for循环外赋值,才能return。

    代码:

        public int deduplication(int[] nums) {
            if (nums.length == 0) return 0;
            Arrays.sort(nums);
            int i = 0;
            for (int j = 1; j < nums.length; j++){
                if (nums[i] != nums[j])
                    nums[++i] = nums[j];
            }
            return i+1;
            
        }
  • 相关阅读:
    BZOJ 2226 [Spoj 5971] LCMSum | 数论拆式子
    BZOJ 2705: [SDOI2012]Longge的问题 | 数论
    BZOJ 1257[CQOI2007]余数之和sum | 数论
    BZOJ 3781: 小B的询问 | 莫队
    文件切割与合并
    [科普贴]为何Flash被淘汰?附Chrome看视频最完美教程!
    JQ模仿select
    JS正则表达式
    Vuejs——Vue生命周期,数据,手动挂载,指令,过滤器
    Vuejs——v-on
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10636170.html
Copyright © 2011-2022 走看看