136. Single Number
2016-07-20 09:53
309 查看
题目
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
分析
由于每个元素都出现两次,只有一个会出现一次,所以将每个元素做异或运算,相同位为0,不同位为1,因此不管两个相同元素相隔多远,顺序异或之后结果均为0,而single number与0异或结果仍为本身。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int result=0;
for(int i=0;i<nums.size();i++)
result ^=nums[i];
return result;
}
};
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
分析
由于每个元素都出现两次,只有一个会出现一次,所以将每个元素做异或运算,相同位为0,不同位为1,因此不管两个相同元素相隔多远,顺序异或之后结果均为0,而single number与0异或结果仍为本身。
class Solution {
public:
int singleNumber(vector<int>& nums) {
int result=0;
for(int i=0;i<nums.size();i++)
result ^=nums[i];
return result;
}
};
相关文章推荐
- c++——指针在数组中的应用
- 视频录制+压缩+合并+清除沙盒缓存
- Android基础之Handler机制学习
- Lucene - 自定义过滤器Filter
- 42 左旋转字符串
- Android EventBus
- 基于c++或C的开源搜索引擎
- 安装 inotify-tools
- 禁用PHP函数,可以对php.ini进行配置
- Codeforces Round #363 (Div. 2) B. One Bomb(模拟)
- Git命令行下自动保存用户名和密码
- amf数据解码
- 内网与外网不能同时上
- Android提高代码质量-工具篇
- 取消GridView/ListView item被点击时的效果 记录学习
- 调用天气Api实现天气查询
- JavaScript的==运算详解
- C#基础-3:委托(Delegate)
- 比较全面的js report汇总
- jQuery EasyUI使用教程之创建复杂的树网格