首页 > 其他 > 详细

leetcode 136

时间:2016-10-05 19:39:41      阅读:165      评论:0      收藏:0      [点我收藏+]

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?

数组中只有一个数只出现一次,其余的数都出现两次,找出出现一次的那个数。采用异或运算来处理。

异或运算的性质:任何一个数字异或它自己都等于0。也就是说,如果我们从头到尾依次异或数组中的每一个数字,那么最终的结果刚好是那个只出现依次的数字,因为那些出现两次的数字全部在异或中抵消掉了。

代码如下:

 

 1 class Solution {
 2 public:
 3     int singleNumber(vector<int>& nums) {   
 4         int n = 0;
 5         for(int i = 0; i < nums.size(); i++)
 6         {
 7             n ^= nums[i];
 8         }
 9         return n;
10     }
11 };

 

leetcode 136

原文:http://www.cnblogs.com/shellfishsplace/p/5932545.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!