Missing number

本文介绍了一种在给定数组中查找缺失数字的方法,数组包含从0到n的不同整数,但缺少其中一个数字。提供了两种解决方案:一种是通过计算总和来找出缺失的数字;另一种则是使用异或操作。这两种方法都能在线性时间内找到答案,并且只使用常量额外空间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Note:

Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?


方法一:

求和相减得到的就是消失的。

[cpp]  view plain  copy
  1. class Solution {  
  2. public:  
  3.     int missingNumber(vector<int>& nums) {  
  4.         int len = nums.size();  
  5.         int sum = (1 + len)*len / 2;  
  6.         int sum2 = 0;  
  7.         for (int n : nums){  
  8.             sum2 += n;  
  9.         }  
  10.         return sum - sum2;  
  11.     }  
  12. };  

方法二:异或

 

137. Single Number II   

260. Single Number III 类似

[cpp]  view plain  copy
  1. class Solution {  
  2. public:  
  3.     int missingNumber(vector<int>& nums) {  
  4.         int res=0;  
  5.         for(int i=0;i<nums.size();i++){  
  6.             res^=(i+1)^nums[i];  
  7.         }  
  8.         return res;  
  9.     }  
  10. };  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值