• 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;
            
        }
  • 相关阅读:
    随意输入一串字符串,显示出现次数最多的字符,以及出现次数
    类似QQ的聊天工程
    Java基础语法
    Java安装环境
    创建纯洁的TableViewCell
    从gitlab下载好cocoapods中遇到的问题
    tableview隐藏多余分割线
    UIBarButtonItem变弹簧
    Dictionary中的结构体转出来
    tableviewcell不允许点击
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10636170.html
Copyright © 2020-2023  润新知