找到所有数组中消失的数字

此博客链接:

找到所有数组中消失的数字

题目链接:https://leetcode-cn.com/problems/find-all-numbers-disappeared-in-an-array/solution/zhao-dao-suo-you-shu-zu-zhong-xiao-shi-de-shu-zi-2/

题目

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

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

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

示例:

输入:
[4,3,2,7,8,2,3,1]

输出:
[5,6]

题解

思路:使用哈希表,把数组下标加一的值存到哈希表的key中,把数组中元素的个数存到value中,然后遍历哈希表中value为0的值,添加到结果中。

代码

class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
         int len=nums.length;
        //  nums=Arraysort(nums);
         Map <Integer,Integer> map=new HashMap();
         List <Integer> list=new ArrayList();
         for(int i=0;i<len;i++)
              map.put(i+1,0);
         for(int i=0;i<len;i++)
         {
                 Integer count=map.get(nums[i]);
                 map.put(nums[i],++count);
                         
         }
         for(Integer str:map.keySet())
             if(map.get(str)==0)
                list.add(str);
         
         return list;
    }
}

结果

 

出来混总是要还的
原文地址:https://www.cnblogs.com/ping2yingshi/p/14143863.html