博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode Missing Number
阅读量:4507 次
发布时间:2019-06-08

本文共 1094 字,大约阅读时间需要 3 分钟。

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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

非常妙的一题

使用xor操作, nums中给出的n个数其范围应该在[0, n]之间(共n+1个)即0.1.2.3...n,然后抽掉了一个数,形成nums中的数字(共n个)。所以使用0.1.2.3...n这n+1个数字和数组内各个元素做xor,n+n+1= 2n+1,这样下来必有一个数找不到和他一致的xor为零的数,这个数就是nums数组中缺少的那个

class Solution {public:    int missingNumber(vector
& nums) { int len = nums.size(); int pos = 0; for (int i=0; i

或者也可以使用数列求和公式

class Solution {public:    int missingNumber(vector
& nums) { int len = nums.size(); double sum_should = (0 + len) * (len + 1) / 2.0; double sum_actual = 0; for (int e : nums) { sum_actual += e; } return sum_should - sum_actual; }};

转载于:https://www.cnblogs.com/lailailai/p/4769386.html

你可能感兴趣的文章
adb命令记录
查看>>
swift初学日志
查看>>
Eclipse上GIT插件_客户端配置
查看>>
JavaScript浏览器对象之二Document对象
查看>>
js 乘除算法 浮点 精度解决办法
查看>>
sqlserver2005版本的mdf文件,还没有log文件,
查看>>
错误“该伙伴事务管理器已经禁止了它对远程/网络事务的支持”解决方案
查看>>
System x 服务器制作ServerGuide U盘安装Windows Server 2008 操作系统 --不格式化盘
查看>>
前端常见跨域解决方案(全)
查看>>
umi---className设置多个样式
查看>>
网页包抓取工具Fiddler工具简单设置
查看>>
周总结报告
查看>>
Selecting Courses POJ - 2239(我是沙雕吧 按时间点建边 || 匹配水题)
查看>>
Win+R指令(2)
查看>>
codeforces 578c - weekness and poorness - 三分
查看>>
数值微分方程
查看>>
动态规划--电路布线(circuit layout)
查看>>
<转>OD常用断点列表
查看>>
描边时消除锯齿SetSmoothingMode
查看>>
15回文相关问题
查看>>