remove duplicates from an unsorted array, return its new length. It doesn't matter what's left beyond the length.
Naive Thinking: 因为是unsorted, 重复的数可能是分开的,不能用两个指针一快一慢进行了。需要用一个set去存已遍历过的。这样是O(n) run time, O(n) space。
import java.util.Set;
import java.util.HashSet;
public class Solution{
public static void main(String args[]){
Solution s = new Solution();
int num[] = {1,5,2,6,8,9,1,1,10,3,2,4,1,3,11,3};
for(int i = 0;i < s.removeDuplicates(num);i++)
System.out.print(num[i] + " ");
System.out.println();
}
public int removeDuplicates(int num[]){
Set<Integer> set = new HashSet<Integer>();
int j = 0;
for(int i = 0;i < num.length;i++)
if(!set.contains(num[i])){
set.add(num[i]);
num[j++] = num[i];
}
return j;
}
}
No comments:
Post a Comment