题目
给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。
找到所有在 [1, n] 范围之间没有出现在数组中的数字。
您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。
示例 :
输入: [4,3,2,7,8,2,3,1]
输出:
[5,6]
标签
解题思路
方法一:哈希
先将数组中出现的数字保存到哈希表中,第二次遍历时,将未在其中的数返回。
方法二:技巧解法
将所有正数作为数组下标,置对应数组值为负值。那么,仍为正数的位置即为(未出现过)消失的数字。
代码
public class Leetcode448 {public static void main(String[] args) {int[] nums = {4, 3, 2, 7, 8, 2, 3, 1};List<Integer> ans = findDisappearedNumbers(nums);System.out.println(ans);}//方法一:哈希public static List<Integer> findDisappearedNumbers(int[] nums) {int len = nums.length;//要返回的答案List<Integer> ans = new ArrayList<>();Map<Integer, Integer> map = new HashMap<>();//将出现的数字进行保存for (int i = 0; i < len; i++) {//只记录一次不重复的数字到mapif (!map.containsKey(nums[i])) {map.put(nums[i], 1);}}for (int i = 1; i <= len; i++) {//遍历1~len,如果map没有包含就添加if (!map.containsKey(i)) {ans.add(i);}}return ans;}//方法二:将所有正数作为数组下标,置对应数组值为负值。那么,仍为正数的位置即为(未出现过)消失的数字。public static List<Integer> findDisappearedNumbers2(int[] nums) {List<Integer> results = new ArrayList<>();for (int i = 0; i < nums.length; i++) {if (nums[Math.abs(nums[i]) - 1] > 0) {nums[Math.abs(nums[i]) - 1] = -nums[Math.abs(nums[i]) - 1];}}for (int i = 0; i < nums.length; i++) {if (nums[i] > 0) {results.add(i + 1);}}return results;}}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/
