Leetcode-448-找到所有数组中消失的数字

Leecode-448-找到所有数组中消失的数字

思路:自哈希

题目描述

给定一个范围在 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;
}

// 左边a b a
// 右边相同 :两个数字的异或
nums[index1] = nums[index1] ^ nums[index2];
nums[index2] = nums[index1] ^ nums[index2];
nums[index1] = nums[index1] ^ nums[index2];
}

}

复杂度分析:

  • 时间复杂度:O(N),这里 N 是数组的长度。(均摊复杂度)
  • 空间复杂度:O(1),这里因为使用异或运算交换数组的元素,故没有使用额外的数组空间。
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信