LeetCode之Find All Numbers Disappeared in an Array

简介: LeetCode之Find All Numbers Disappeared in an Array

1、题目

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.


Find all the elements of [1, n] inclusive that do not appear in this array.


Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.


Example:


Input:

[4,3,2,7,8,2,3,1]

Output:

[5,6]

Input:

[0]

Output:

[1]


2、代码实现

public class Solution {

    public List<Integer> findDisappearedNumbers(int[] nums) {

 List<Integer> list = new ArrayList<Integer>();

 if (nums == null || nums.length == 0)

  return list;

 Map<Integer, Integer> map = new HashMap<Integer, Integer>();

    for (int  i = 0;  i < nums.length; ++i) {

     map.put(nums[i], 2);

    }

    for (int i = 1; i <= nums.length; ++i) {

     Integer in = map.get(i);

         if (in == null) {

          list.add(i);

         }

     }

  return list;

}

}


3、总结

当我们需要找到数组集合里面没有包含哪个元素的时候,我们可以采用HashMap来解决这个问题

比如{1, 2,4, 2, 5}

还有就是找2个字符串里面第一个不重复元素的问题,我们可以采用HashMap来解决这个问题

s = "leetcode"

return 0.

s = "loveleetcode",

return 2.

或者找字符数组里面唯一一个重复的字符都可以采用HashMap来解决这个问题

 


相关文章
|
8月前
Leetcode Find Minimum in Rotated Sorted Array 题解
对一个有序数组翻转, 就是随机取前K个数,移动到数组的后面,然后让你找出最小的那个数,注意,K有可能是0,也就是没有翻转。
28 0
|
10月前
|
存储 C++ Python
LeetCode刷题---Add Two Numbers(一)
LeetCode刷题---Add Two Numbers(一)
|
存储 算法 安全
LeetCode - #2 Add Two Numbers
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
LeetCode - #2 Add Two Numbers
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
|
算法 Python
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
|
算法 测试技术
LeetCode 88. 合并两个有序数组 Merge Sorted Array
LeetCode 88. 合并两个有序数组 Merge Sorted Array
LeetCode 1380. 矩阵中的幸运数 Lucky Numbers in a Matrix
LeetCode 1380. 矩阵中的幸运数 Lucky Numbers in a Matrix
|
人工智能 索引
LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
LeetCode Contest 178-1365. 有多少小于当前数字的数字 How Many Numbers Are Smaller Than the Current Number
LeetCode Contest 178-1365. 有多少小于当前数字的数字 How Many Numbers Are Smaller Than the Current Number
LeetCode 189. 旋转数组 Rotate Array
LeetCode 189. 旋转数组 Rotate Array