首页 > 其他 > 详细

【3_136】Single Number

时间:2015-12-11 18:39:15      阅读:259      评论:0      收藏:0      [点我收藏+]
感谢:http://www.cnblogs.com/changchengxiao/p/3413294.html

Single Number

Total Accepted: 103007 Total Submissions: 217483 Difficulty: Medium

 

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?

 

琢磨了很久没找到满足题目的两个要求:O(1)和不开空间。实在没办法才上网查找,原来是汇编语言的知识,而且C++中还可以直接用。

 

原文:

o(n)的算法只能是线性扫描一遍,可能的相法是位运算。对于异或来说:

1. 异或运算是可交换,即 a ^ b = b ^ a

2. 0 ^ a = a

那么如果对所有元素做异或运算,其结果为那个出现一次的元素,理解是a1 ^ a2 ^ ....

 

所以说,这是终极解法。

 

 1 public class Solution {
 2     public int singleNumber(int[] A) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         if(A == null || A.length == 0){
 5             return 0;
 6         }
 7         int result = A[0];
 8         
 9         for(int i = 1; i < A.length; i++){
10             result ^= A[i];
11         }
12         return result;
13     }
14 }

 

LeetCode很有趣,希望明天可以自己想出来!

【3_136】Single Number

原文:http://www.cnblogs.com/QingHuan/p/5039577.html

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