|
| 1 | +给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。 |
| 2 | +找到所有在 [1, n] 范围之间没有出现在数组中的数字。 |
| 3 | +示例: |
| 4 | +```python |
| 5 | +输入: |
| 6 | +[4,3,2,7,8,2,3,1] |
| 7 | +输出: |
| 8 | +[5,6] |
| 9 | +``` |
| 10 | +#### 方法一:使用哈希表 |
| 11 | +* 遍历数组,将元素存入字典中。 |
| 12 | +* 遍历 1-n,判断哪个元素不存在字典。 |
| 13 | + |
| 14 | +```python |
| 15 | +def findDisappearedNumbers(nums): |
| 16 | + hash_table = {} |
| 17 | + dissappear_nums = [] |
| 18 | + for num in nums: |
| 19 | + hash_table[num] = '' |
| 20 | + for item in range(1, len(nums)+1): |
| 21 | + if item not in hash_table: |
| 22 | + dissappear_nums.append(item) |
| 23 | + return dissappear_nums |
| 24 | +``` |
| 25 | + |
| 26 | +#### 方法二:原地遍历标记数组元素 |
| 27 | +将出现的数字所在的下标的元素变成负数,这样遍历完输入数组之后,剩余的没有变成负数的下标就是缺失的数值。 |
| 28 | +比如: |
| 29 | +```python |
| 30 | +[3, 3, 2, 1, 4, 5, 6, 4] |
| 31 | +第一个元素值为3,正常情况1~n [1, 2, 3, 4, 5, 6, 7, 8] |
| 32 | +3应该出现在索引2=3-1的位置上,所以把这个位置的数字变成负数。 |
| 33 | +[3, 3, -2, 1, 4, 5, 6, 4] |
| 34 | +就表示这个数字已经出现过了。 |
| 35 | +当遍历到-2时,其实也就是2,就把索引为1=2-1的元素变为负数, |
| 36 | +表示2这个数字已经出现过了。 |
| 37 | +[3, -3, -2, 1, 4, 5, 6, 4],如此下去, |
| 38 | +所有出现过的元素,应该在的位置的数字全都变为负数了 |
| 39 | +[-3, -3, -2, -1, -4, -5, 6, 4] |
| 40 | +所以,元素为正数的最后两位,实际也就是7,和8没有出现。 |
| 41 | +``` |
| 42 | +代码 |
| 43 | +```python |
| 44 | +def findDisappearedNumbers(nums): |
| 45 | + disappear_nums = [] |
| 46 | + for num in nums: |
| 47 | + num = abs(num) |
| 48 | + if nums[num-1] > 0: |
| 49 | + nums[num-1] = -nums[num-1] |
| 50 | + for index, item in enumerate(nums): |
| 51 | + if item > 0: |
| 52 | + disappear_nums.append(index+1) |
| 53 | + return disappear_nums |
| 54 | +``` |
0 commit comments