1.题目

给定一个范围在 1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。

找到所有在 [1, n] 范围之间没有出现在数组中的数字。

您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。

示例:

  1. 输入:
  2. [4,3,2,7,8,2,3,1]
  3. 输出:
  4. [5,6]

2.思路

官方给的解答是利用哈希表,这里贴个答案吧,不太会这道题~

  1. public List<Integer> findDisappearedNumbers(int[] nums) {
  2. int n = nums.length;
  3. for (int num : nums) {
  4. int x = (num - 1) % n;
  5. nums[x] += n;
  6. }
  7. List<Integer> ret = new ArrayList<Integer>();
  8. for (int i = 0; i < n; i++) {
  9. if (nums[i] <= n) {
  10. ret.add(i + 1);
  11. }
  12. }
  13. return ret;
  14. }

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/solution/zhao-dao-suo-you-shu-zu-zhong-xiao-shi-d-mabl/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。