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

Single Number 解答

时间:2015-09-15 06:58:25      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:

Question

Given an array of integers, every element appears twice except for one. Find that single one.

Solution 1 -- Set

We can use a hash set to record each integer‘s appearing time. Time complexity O(n), space cost O(n)

 1 public class Solution {
 2     public int singleNumber(int[] nums) {
 3         Set<Integer> counts = new HashSet<Integer>();
 4         int length = nums.length, result = nums[0];
 5         for (int i = 0; i < length; i++) {
 6             int tmp = nums[i];
 7             if (counts.contains(tmp))
 8                 counts.remove(tmp);
 9             else
10                 counts.add(tmp);
11         }
12         for (int tmp : counts)
13             result = tmp;
14         return result;
15     }
16 }

Solution 2 -- Bit Manipulation

The key to solve this problem is bit manipulation. XOR will return 1 only on two different bits. So if two numbers are the same, XOR will return 0. Finally only one number left.

1 public int singleNumber(int[] A) {
2     int x = 0;
3     for (int a : A) {
4         x = x ^ a;
5     }
6     return x;
7 }

Single Number 解答

标签:

原文地址:http://www.cnblogs.com/ireneyanglan/p/4809029.html

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