Wednesday, March 29, 2017

Remove Duplicate Numbers in Array

There are 2 ways to solve this kind of question: HashMap and Two Pointers. However, the description asks us to do it in place, so we can only tow pointers method. Which has O(nlogn) time complexity and O(1) space complexity.


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.


public class Solution {
    /**
     * @param nums an array of integers
     * @return the number of unique integers
     */
    public int deduplication(int[] nums) {
        // Write your code here
        //[1, 1, 2, 3, 4, 4]
        //          s     f
        //[1, 2, 3, 4, ]
        
        if (nums == null || nums.length == 0) return 0;
        if (nums.length == 1) return 1;
        Arrays.sort(nums);
        int slow = 0;
        int fast;
        for (fast = 1; fast < nums.length; fast++) {
            if (nums[fast] != nums[slow]) {
                nums[++slow] = nums[fast];
            }
        }
        //Since slow represents index starts from zero
        return slow + 1;
    }
}



No comments:

Post a Comment