首页 > 其他分享 >leetcode-268-easy

leetcode-268-easy

时间:2022-10-31 20:57:14浏览次数:45  
标签:nums int since number range numbers easy 268 leetcode

Missing Number

Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.

Example 1:

Input: nums = [3,0,1]
Output: 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
Example 2:

Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
Example 3:

Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.
Constraints:

n == nums.length
1 <= n <= 104
0 <= nums[i] <= n
All the numbers of nums are unique.
Follow up: Could you implement a solution using only O(1) extra space complexity and O(n) runtime complexity?

思路一:观察数组的分布范围,刚好是 [0, n),把数组全部相加,再减去[0, n],由于数组少了一个值,所以结果一定是所求解的负数,因为少了那个值

public int missingNumber(int[] nums) {
    int x = -nums.length;
    for (int i = 0; i < nums.length; i++) {
        x += nums[i];
        x -= i;
    }

    return -x;
}

思路二:用 set 统计,然后遍历也是一种思路,但是需要额外的空间

标签:nums,int,since,number,range,numbers,easy,268,leetcode
From: https://www.cnblogs.com/iyiluo/p/16845748.html

相关文章

  • leetcode-500-easy
    KeyboardRowGivenanarrayofstringswords,returnthewordsthatcanbetypedusinglettersofthealphabetononlyonerowofAmericankeyboardliketheim......
  • leetcode-1356-easy
    SortIntegersbyTheNumberOf1BitsYouaregivenanintegerarrayarr.Sorttheintegersinthearrayinascendingorderbythenumberof1'sintheirbinar......
  • AI人脸检测识别EasyCVR视频融合平台告警预案的配置操作与使用
    我们在前期的文章中为大家介绍了EasyCVR新增的告警预案功能,感兴趣的用户可以戳这篇文章:《AI人脸检测智能视频融合平台EasyCVR新增告警预案功能》。  告警预案可以根......
  • EasyCode
    文章目录​​前提准备​​​​1、idea安装easycode插件​​​​本地安装​​​​在线安装(推荐)​​​​2、idea添加数据库​​​​一、easyCode表生成​​​​单表生成:选择......
  • EasyCode
    文章目录​​前提准备​​​​1、idea安装easycode插件​​​​本地安装​​​​在线安装(推荐)​​​​2、idea添加数据库​​​​一、easyCode表生成​​​​单表生成:选择......
  • leetcode-1-easy
    TwoSumGivenanarrayofintegersnumsandanintegertarget,returnindicesofthetwonumberssuchthattheyadduptotarget.Youmayassumethateachinp......
  • C++&Python 描述 LeetCode 1.两数之和
    C++&Python描述LeetCode1.两数之和  大家好,我是亓官劼(qíguānjié),在【亓官劼】公众号、、GitHub、B站、华为开发者论坛等平台分享一些技术博文。放弃不难,但坚持......
  • SpringBoot如何用easyPOI导出excel文件
    在工作中,经常需要我们用Java代码导出一些数据,保存在Excel中。这是非常实用的Excel导出功能,如果我们用SpringBoot结合EasyPOI框架,可以非常方便地实现这个功能。在maven项目中......
  • dp-leetcode152
    动态规划问题,存在重叠子问题/***<p>给你一个整数数组<code>nums</code>&nbsp;,请你找出数组中乘积最大的非空连续子数组(该子数组中至少包含一个数字),并返回该子数......
  • LeetCode刷题记录.Day1
    二分查找基础:二分查找题目链接 LoadingQuestion...-力扣(LeetCode)最开始的题解:classSolution{public:intsearch(vector<int>&nums,inttarget){......