Description
Given an array of integers, remove the duplicate numbers in it.
You should:
- Do it in place in the array.
- Move the unique numbers to the front of the array.
- Return the total number of the unique numbers.
Input:
nums = [1,3,1,4,4,2]
Output:
[1,3,4,2,?,?]
4
Challenge
- Do it in O(n) time complexity.
- Do it in O(nlogn) time without extra space.
O(n) time, O(n) space
思路2: 双指针法
O(nlogn) time, O(1) extra space
先对数组排序,再用快指针遍历整个数组,慢指针改变数组使其只包含非重复数字。
注意:
快指针放在for循环里。慢指针在for循环外赋值,才能return。
代码:
public int deduplication(int[] nums) { if (nums.length == 0) return 0; Arrays.sort(nums); int i = 0; for (int j = 1; j < nums.length; j++){ if (nums[i] != nums[j]) nums[++i] = nums[j]; } return i+1; }