码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 136. Single Number && 137. Single Number II

时间:2015-01-17 17:43:10      阅读:110      评论:0      收藏: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?

异或运算应用:

  异或运算满足交换律和结合律, 通过交换元素(如插入排序等)可以使得相同元素相邻,

(x, x), (y, y), ..., sigle, ... , (z, z)

所有元素异或后:(x ^ x) ^ ... ^ single ^ (z ^ z) = 0 ^ ... ^ single ^ ... ^ 0 = single 

1 int singleNumber(int A[], int n) 
2     {
3         int single = 0;
4         
5         for (int i = 0; i < n; i++)
6             single ^= A[i];
7         
8         return single; 
9     }

 

leetcode 136. Single Number && 137. Single Number II

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4230658.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!