首页 > 其他 > 详细

Leetcode 136. Single Number

时间:2017-08-05 22:42:40      阅读:199      评论: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?

  这道题目的时间复杂度必须是O(n),并且空间复杂度为O(1),使得不能用排序方法,也不能使用map数据结构。那么只能另辟蹊径,需要用位操作Bit Operation来解此题。

  这里用到逻辑异或的两个性质:

  一:相同的两个int型数据 ^ 之后为0

  二:逻辑异或满足交换律、结合律,即对于题目中的数组可以看成是先把元素排好序相同的放在一块进行异或运算,与元素的参加运算的顺序无关。

  逻辑异或的运算真值表:

输入
运算符
输入
结果
1
0
1
1
1
0
0
0
0
0
1
1

 代码:

public class Solution {
    public int singleNumber(int[] nums) {
        int ans = 0;
        for(int n:nums){
            ans ^= n;
        }
        return ans;
    }
}

 

Leetcode 136. Single Number

原文:http://www.cnblogs.com/mxk-star/p/7291703.html

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