思路:自哈希
题目描述
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
1 2 3 4 5
| 输入: [4,3,2,7,8,2,3,1]
输出: [5,6]
|
方法:自哈希
这里由于数组元素限定在数组长度的范围内,因此,我们可以通过一次遍历:
让数值 1 就放在索引位置 0 处;
让数值 2 就放在索引位置 1 处;
让数值 3 就放在索引位置 2 处;
再次遍历一遍数组,如果当前 索引+1 != 当前值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class Solution { public List<Integer> findDisappearedNumbers(int[] nums) { List<Integer> res = new ArrayList<>();
int len = nums.length;
for (int i = 0; i < len; i++) { while (nums[nums[i] - 1] != nums[i]){ swap(nums,i,nums[i] - 1); } }
for (int i = 0; i < len; i++) { if (nums[i] != i + 1){ res.add(i + 1); } }
return res; }
private void swap(int[] nums,int index1,int index2){ if (index1 == index2){ return; }
nums[index1] = nums[index1] ^ nums[index2]; nums[index2] = nums[index1] ^ nums[index2]; nums[index1] = nums[index1] ^ nums[index2]; } }
|
复杂度分析:
- 时间复杂度:O(N),这里 N 是数组的长度。(均摊复杂度)
- 空间复杂度:O(1),这里因为使用异或运算交换数组的元素,故没有使用额外的数组空间。
打赏