136. Single Number
2016-06-06 00:38
218 查看
136. Single Number
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?
Analysis:
这道题可使用异或运算求解,主要用到以下性质:
1.异或运算符合交换律和结合律。即a^b=b^a; (a^b)^c=(a^b)^c
2.a^a=0
补充:异或运算的其他使用:使特定位翻转(^1),使特定位保持不变(^0)
Source Code(C++):
#include <iostream> #include <vector> using namespace std; class Solution { public: int singleNumber(vector<int>& nums) { if (nums.empty()){ return -1; } int single_number = nums.at(0); for (int i=1; i<nums.size(); i++){ single_number ^= nums.at(i); } return single_number; } }; int main() { Solution sol; vector<int> v; cout << sol.singleNumber(v); return 0; }
相关文章推荐
- 管道流PipedInputStream与PipedOutputStream操作实例
- Struts2实现文件批量上传
- Java实现表达式的运算
- Android中ProgressDialog的使用
- tp vendor遇到的坑
- Linux内核之数据双链表
- 享元模式 Java
- TCP 的那些事儿系列
- C/C++的内存布局
- c++第七次上机作业
- bzoj 1089
- c++作业七
- PHP Socket实现websocket(二)Socket函数
- C++ 虚函数表
- SPringMVC各层浅析
- Ralink RT5350 GPIO配置(坑了个大爹的)
- C++第7次上机作业
- UVa 12545 Bits Equalizer (贪心)
- hdu1372 BFS求最短路径长度
- java中Scanner类nextLine()和next()的区别和使用方法