Remove Duplicate Numbers in Array解题报告

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:

Given nums = [1,3,1,4,4,2], you should:

Move duplicate integers to the tail of nums => nums = [1,3,4,2,?,?].
Return the number of unique integers in nums => 4.
Actually we don't care about what you place in ?, we only care about the part which has no duplicate integers.

Link:

http://www.lintcode.com/en/problem/remove-duplicate-numbers-in-array/

解题思路:

这道题意思是去除数组中的重复数字,并且把不重复的数字移动到数组前面,并且返回不重复数字的个数。
要求do it in place in the array, 也就是在O(n)的空间内完成。

解题方法:

所以解题方法有2中:
1)O(n)时间,O(n)空间:用哈希表去重,再把哈希表里的元素重新放进数组里面,记录数量。
2)O(nlogn)时间,O(1)空间:首先对数组排序,然后用快慢指针解决,快慢指针在同一起点,因为已经排序所以重复数字会排在一起,所以快指针一个个读取数字,每当读到与慢指针不同的数字,慢指针首先往后走一格(保存之前的数),然后再把快指针所在的数放到慢指针的位置(获得到新的数)。不停重复这个过程直到快指针走完数组。慢指针所在的位置就是最后一个unique number的位置。

Tips:

nums[++count] = nums[i];

Time Complexity:

方法1:O(n)时间 O(n)空间
方法2:O(nlogn)时间 O(1)空间

完整代码:

方法1
int count = 0; if(nums.size() == 0) return count; unordered_map maps; for(int i : nums) maps[i] = true; for(auto a : maps) nums[count++] = a.first; return count;
方法2
int count = 0; if(nums.size() == 0) return count; sort(nums.begin(), nums.end()); for(int i = 0; i < nums.size(); i++) { if(nums[i] != nums[count]) nums[++count] = nums[i]; } return count+1;

你可能感兴趣的:(Remove Duplicate Numbers in Array解题报告)