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

LeetCode-Single Number

时间:2015-03-17 02:00:44      阅读:102      评论: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?

 

  看到这个题目的时候,由于我第一语言是Java,第一反应是使用HashSet实现。

 

 1 public class Solution {
 2     public int singleNumber(int[] A) {
 3            HashSet<Integer> set = new HashSet<Integer>();
 4 
 5         for (int i = 0; i < A.length; i++) {
 6             if (!set.add(A[i])) {
 7                 set.remove(A[i]);
 8                 continue;
 9             }
10             set.add(A[i]);
11         }
12 
13         return set.iterator().next();
14     }
15 }

 

提交后发现超时了:( 。

 

于是又使用HashMap尝试

 1 public class Solution {
 2     public int singleNumber(int[] A) {
 3         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
 4         for (int i : A) {
 5             if (map.get(i) != null) {
 6                 map.remove(i);
 7                 continue;
 8             }
 9 
10             map.put(i, i);
11         }
12 
13         return map.keySet().iterator().next();
14     }
15 }

居然就通过了 :(.

据我所知,HashSet是使用HashMap实现的,为何就有如此差异呢。

 

而后看见Discuss中有号称4行的答案 

1 public class Solution {
2     public int singleNumber(int[] A) {
3        int n = 0;
4         for (int i : A) {
5             n ^= i;
6         }
7         return n;
8     }
9 }

巧妙的使用了位运算,异或的特性将相同的数字清零,而后剩下single num。

完全没有想到这种方法,安慰自己是写得少的关系,还需多多练习,多多积累。

 

LeetCode-Single Number

标签:

原文地址:http://www.cnblogs.com/sluggard/p/4343396.html

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