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

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

Missing Number

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  for adding this problem and creating all test cases.

 

这题需要技巧,利用异或。

先将nums的数作异或得到x1;

将0-n+1都作异或得到x2;

missing number 就是x1^x2。

为什么呢?

假设缺少的值为A,则x2=x1^A,那么x1^x2=x1^(x1^A)=(x1^x1)^A=0^A=A,得证。

1 class Solution { 2 public: 3     int missingNumber(vector
& nums) { 4 int result; 5 int x1=nums[0]; 6 for(int i=1;i

 

转载于:https://www.cnblogs.com/Sean-le/p/4797911.html

你可能感兴趣的文章
JSP取得绝对路径
查看>>
Python Module_os_操作系统
查看>>
最新Do Not Track标准问世:网站都应尊重用户选择
查看>>
逾半数全球商业领袖认同智能自动化,但首先要解决员工的抵触情绪
查看>>
被忽视的Web安全漏洞:如何识别和解决?
查看>>
SDN网络的构建及通信业务与光纤引入
查看>>
对冷却系统进行全面分析
查看>>
撬动智能家居市场 智慧家庭“最强大脑”被激活
查看>>
聊聊springcloud的GatewayControllerEndpoint
查看>>
聊聊sentinel的SentinelResourceAspect
查看>>
聊聊flink的SpoutWrapper
查看>>
聊聊flink的StateDescriptor
查看>>
git 使用教程,常用命令
查看>>
使用SVI实现Vlan间路由
查看>>
Linux学习笔记5月28日任务
查看>>
解决Td内容为空时不显示边框的问题-兼容IE、firefox、chrome
查看>>
SylixOS x86中断探测(二)
查看>>
HDFS总结
查看>>
scala 中导出excel
查看>>
http长轮询&短轮询
查看>>