LeetCode Missing Number
2015-08-29 16:54
162 查看
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<int>& nums) { int len = nums.size(); int pos = 0; for (int i=0; i<len; i++) { pos ^= nums[i] ^ i; } pos ^= len; return pos; } };
或者也可以使用数列求和公式
class Solution { public: int missingNumber(vector<int>& 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; } };
相关文章推荐
- 学习笔记 五 css
- Django最佳实践(中文版)
- bp神经网络算法中的权值修改问题
- 友元,虚函数,纯虚函数,静态函数
- ubuntu下安装国际版QQ
- js的replaceAll() (转)
- STM32之定时器prescaler
- [机器学习实战]--朴素贝叶斯过滤垃圾邮件
- Leetcode 222: Count Complete Tree Nodes
- 软件静默安装命令大全
- Javascript、Jquery获取浏览器和屏幕各种高度宽度
- 常量、字段、方法、属性和索引器(C#)
- Long CLick 和Long Press区别
- 【前端学习笔记】JS学习基础
- 飞思卡尔智能车准备篇
- 常量、字段、方法、属性和索引器(C#)
- 技术之路的三大模块+常用软件+常见问题
- Android主题切换—夜间/白天模式探究
- 图像处理之霍夫变换(直线检测算法)
- dump文件的使用