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

 

posted @ 2019-04-01 15:01  IreneZh  阅读(148)  评论(0编辑  收藏  举报