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;
            
        }
  • 相关阅读:
    《认知突围》摘抄
    《java多线程编程核心技术》----ThreadLocal
    java有必要记录的东西
    spring源码几个servlet功能的介绍
    基于openapi3.0的yaml文件生成java代码的一次实践
    Android攻城狮 调试
    Android攻城狮 http协议
    Android攻城狮 Android中更新UI的几种方式
    Android攻城狮 Handler与子线程
    Android攻城狮Handler简介
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10636170.html
Copyright © 2011-2022 走看看