Missing Number(讲解一个非常好的方法)
来源:互联网 发布:陈翔六点半 知乎 编辑:程序博客网 时间:2024/06/04 09:33
题目名称
Missing Number—LeetCode链接
描述
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?
分析
考虑到将原数组排序后,如果不缺失元素,数组下标值和元素值是相等的,所以常规思路就是将数组排序,然后根据位置查找,如果丢失的是最后一个数字,则返回最后一个数字;否则从数组头部开始遍历,直到找到值与下标不相符的,返回下标数字。
C++代码
class Solution {public: int missingNumber(vector<int>& nums) { sort(nums.begin(),nums.end()); int size = nums.size(); if(nums[size-1]==size-1) return size; for(int i=0;i<size;i++){ if(nums[i]!=i) return i; } }};
总结
这里给出一个非常棒的答案,不需要将原数组排序,而采用异或操作符^。先给出代码,再做解释:
class Solution {public: int missingNumber(vector<int>& nums) { int result = 0; for (int i = 0; i < nums.size(); i++) result ^= nums[i]^(i+1); return result; }};
The operation of xor is commutative and associative. That is A ^ B = B^A and (A ^ B) ^ C = A ^ (B ^ C). Therefore, A^C^B^A^C = A^A^C^C^B = B. So for this code, the order of the numbers does not matter at all.
上段内容是这个代码的作者的解释,很好懂,举个例子,给定一个数组:
4,2,0,1
result初始值为0,做异或操作就是:0^(4^1)^(2^2)^(0^3)^(1^4)=3.
答案看上去很巧妙,其实思路很简单,给定的数组肯定缺失一个数字,那么我对数组所有元素(4,2,0,1)和不缺失的情况(0,1,2,3,4)中所有元素进行异或连接操作,肯定能得到缺失的那个数字。
- Missing Number(讲解一个非常好的方法)
- 非常好的webSocket讲解
- 非常好的websocket讲解2
- 一个非常好的测试
- 非常好的一个网址
- 一个 非常好的网站
- Missing number(5166)
- 一个或得Properties的方法,感觉非常好
- 表驱动方法(非常好的数据结构)
- CSU 1090: Number Transformation 一个非常好的优先队列打表
- 非常好的objective-c语法讲解
- 一篇讲解android线程非常好的文章
- Missing Number 丢失的数字
- socket通信简介(讲解非常好!)----转载
- 一个非常好的CVS站点
- 一个非常好用的导航
- 非常好的一个日期控件
- 一个非常好的网上书店!
- 精华--CentOS多网卡配置
- tomcat server.xml配置详解
- Oracle 实例恢复
- Cookie
- 关于Cannot find or open the PDB file ntdll.dll gdi32.dll user32.dll 的解决办法
- Missing Number(讲解一个非常好的方法)
- UML之包图
- 自抛自打练习收小臂
- iOS启动画面延时
- 好的架构源于不停地衍变,而非设计(确实如此)
- 网站推荐-不断更新
- java多态
- opencv2-第五章-floodFill漫水填充算法
- 0000-00-00 创建书语的粑粑的博客索引