LeetCode之Missing Number

简介: LeetCode之Missing Number

1、题目

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.


For example,

Given nums = [0, 1, 3] return 2.


Given  nums  =  [0]  return  1


2、代码实现

public class Solution {

   public  int missingNumber(int[] nums) {

 if (nums == null) {

  return 0;

 }

 int result = 0;

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

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

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

       }

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

        Integer in = map.get(i);

        if (in == null) {

         return i;

        }

       }

 return result;

   }

}


3、注意的地方

这个地方需要注意

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

        Integer in = map.get(i);

        if (in == null) {

         return i;

        }

       }

一定要记得写 i <= nums.length ,不是i < length


相关文章
|
6月前
|
算法
Leetcode 313. Super Ugly Number
题目翻译成中文是『超级丑数』,啥叫丑数?丑数就是素因子只有2,3,5的数,7 14 21不是丑数,因为他们都有7这个素数。 这里的超级丑数只是对丑数的一个扩展,超级丑数的素因子不再仅限于2 3 5,而是由题目给定一个素数数组。与朴素丑数算法相比,只是将素因子变了而已,解法还是和朴素丑数一致的。
66 1
|
1天前
|
存储 算法
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
【LeetCode力扣】单调栈解决Next Greater Number(下一个更大值)问题
6 0
|
6月前
|
存储
Leetcode Single Number II (面试题推荐)
给你一个整数数组,每个元素出现了三次,但只有一个元素出现了一次,让你找出这个数,要求线性的时间复杂度,不使用额外空间。
22 0
|
11月前
|
C++ 容器
【PAT甲级 - C++题解】1144 The Missing Number
【PAT甲级 - C++题解】1144 The Missing Number
42 0
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
LeetCode contest 190 5417. 定长子串中元音的最大数目 Maximum Number of Vowels in a Substring of Given Length
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 136. 只出现一次的数字 Single Number
LeetCode 136. 只出现一次的数字 Single Number
LeetCode contest 177 5169. 日期之间隔几天 Number of Days Between Two Dates
LeetCode contest 177 5169. 日期之间隔几天 Number of Days Between Two Dates
|
1天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
8 0
|
1天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
11 0

热门文章

最新文章