标签:size ret nlogn front continue 位置 oid car i++
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.
You don‘t need to keep the original order of the integers.
Given nums = [1,3,1,4,4,2]
, you should:
[1,3,4,2,?,?]
.4
.Actually we don‘t care about what you place in ?
, we only care about the part which has no duplicate integers.
1.O(n) time: 用HashSet来确认有过没,有过就swap(切记这里要做一个 i--的操作,因为你把后面没有检验过的数换到这里了,要重新确认当前位置);没有就加入set,继续。
2.O(n) time:用HashSet。一开始就把所有数字都加入HashSet。之后遍历set(切记set没有set.get(i)方法,只能用iterator的那个冒号方法),放到数组的最前面。
3.O(nlogn)time, but no extra space: 先sort,把一样的数字聚集到一起。再用一个int cntDistct 来同时做计数和指针,如果找到独特的数,就直接替换到前面指针的位置。
1. HashSet+swap
public class Solution { /* * @param nums: an array of integers * @return: the number of unique integers */ public int deduplication(int[] nums) { // write your code here Set<Integer> set = new HashSet<Integer>(); int countDup = 0; for (int i = 0; i < nums.length - countDup; i++) { if (!set.contains(nums[i])) { set.add(nums[i]); } else { swap(nums, i, nums.length - 1 - countDup); countDup++; i--; } } return nums.length - countDup; } private void swap (int[] nums, int idx1, int idx2) { int temp = nums[idx1]; nums[idx1] = nums[idx2]; nums[idx2] = temp; } }
2. HashSet
public class Solution { /* * @param nums: an array of integers * @return: the number of unique integers */ public int deduplication(int[] nums) { // write your code here Set<Integer> set = new HashSet<Integer>(); for (int i = 0; i < nums.length; i++) { set.add(nums[i]); } int i = 0; for (Integer number : set) { nums[i++] = number; } return set.size(); } }
3. sort
public class Solution { /* * @param nums: an array of integers * @return: the number of unique integers */ public int deduplication(int[] nums) { // write your code here Arrays.sort(nums); int countDis = 0; for (int i = 0; i < nums.length; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } nums[countDis++] = nums[i]; } return countDis; } }
lintcode521- Remove Duplicate Numbers in Array- easy
标签:size ret nlogn front continue 位置 oid car i++
原文地址:http://www.cnblogs.com/jasminemzy/p/7771613.html