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

Leetcode 136. Single Number

时间:2017-08-05 22:44:36      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:并且   googl   hat   where   结果   map   cti   algorithm   需要   

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

标签:并且   googl   hat   where   结果   map   cti   algorithm   需要   

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

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