Leetcode NO.136 Single Number
2015-09-22 06:21
204 查看
本题题目要求如下:
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和一个数字异或,结果为该数字。。所以可以写出一下的代码:
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和一个数字异或,结果为该数字。。所以可以写出一下的代码:
class Solution { public: int singleNumber(vector<int>& nums) { int res = 0; for (int i = 0; i < nums.size(); ++i) { res ^= nums[i]; } return res; } };
相关文章推荐
- 轻量级 js取色器 JSColor
- 约翰.麦卡锡继承图灵遗愿继续推进人工智能(AI)研究
- Windows下搭建Apache服务器与PHP
- LeetCode Number of 1 Bits
- Merge k Sorted Lists 解答
- Windows下编译C语言文件
- 某位网友对国内计算机教育的反思,写得太好了!
- learn python in 10 minutes
- xUtils
- HBase 1.1.2安装(伪分布式)
- fastjson是阿里巴巴的开源JSON解析库
- centos开机启动
- Leetcode Add Two Numbers
- 华为教小米如何做人:雷军吹牛逼遭通信博士打脸
- *LeetCode-Search in Rotated Sorted Array
- Leetcode Add Binary
- EventBus实现activity跟fragment交互数据
- EventBus实现activity跟fragment交互数据
- 黑马程序员——利用swap函数研究C的指针
- 汉诺塔