521.Remove Duplicate Numbers in Array
1.Description(Medium)
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.
Notice
You don't need to keep the original order of the integers.
Example
Givennums=[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.
Do it in O(n) time complexity.
Do it in O(nlogn) time without extra space.
2.Code
Solution 1:HashSet ,O(n) time, O(n) space
Solution 2:In place O(nlogn) time, O(1) extra space
http://www.jiuzhang.com/solutions/remove-duplicate-numbers-in-array/
这个题目分array有没有sorted.
1.如果已经是sorted的话,最好的方法是就是用一个prev记录前面的,然后遍历,直接加进result,不必要浪费O(n) 的space 去建立一个hashset.
2.如果没有sorted,就是这个题,第一种是时间花费O(n),空间花费O(n)建一个hashset.
Last updated