268. Missing Number(重要!)
2016-07-13 16:46
239 查看
Given an array containing n distinct numbers taken from
find the one that is missing from the array.
For example,
Given nums =
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
方法一:
求和相减得到的就是消失的。
class Solution {
public:
int missingNumber(vector<int>& nums) {
int len = nums.size();
int sum = (1 + len)*len / 2;
int sum2 = 0;
for (int n : nums){
sum2 += n;
}
return sum - sum2;
}
};
方法二:异或
跟
class Solution {
public:
int missingNumber(vector<int>& nums) {
int res=0;
for(int i=0;i<nums.size();i++){
res^=(i+1)^nums[i];
}
return res;
}
};
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?
方法一:
求和相减得到的就是消失的。
class Solution {
public:
int missingNumber(vector<int>& nums) {
int len = nums.size();
int sum = (1 + len)*len / 2;
int sum2 = 0;
for (int n : nums){
sum2 += n;
}
return sum - sum2;
}
};
方法二:异或
跟
137. Single Number II
260. Single Number III 类似
class Solution {public:
int missingNumber(vector<int>& nums) {
int res=0;
for(int i=0;i<nums.size();i++){
res^=(i+1)^nums[i];
}
return res;
}
};
相关文章推荐
- java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder 异常
- 116 - Unidirectional TSP
- ubuntu详细教程[软件安装,命令大全,常用快捷键]
- idea操作快捷键
- UVa699 The Falling Leaves
- Android 中 requestWindowFeature()的应用
- 深度学习和自然语言处理的注意机制和记忆模型
- 算法竞赛经典入门第三章习题
- sql server 游标的使用方法
- SQL笔记
- 一个perfect 的解决 阴影拉伸的方法 shadow map strech
- LVS的四种模式的实现
- Spark学习笔记#1-快速入门
- animate.css动画库使用方法介绍
- org.hibernate.HibernateException: /hibernate.cfg.xml not found
- 支付宝提示:由于您的设备缺少根目录,无法校验该访问站点的安全性,可能存在风险,请选择是否继续
- There is no getter for property "name" in java.lang.String
- Linux基础(4)之文本处理
- Servlet 3.0 新特性详解
- Mondrian 4 测试的简单demo(Saiku简单测试Schema文件)