Single Number

题目:

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

 

 

解法一: bit manipulate

1 public class Solution {
2     public int singleNumber(int[] nums) {
3            int ans = 0;
4         for (int i = 0; i < nums.length; i++) ans ^= nums[i];
5         return ans;
6     
7         
8     }
9 }

 

因为A XOR A = 0,且XOR运算是可交换的,于是,对于实例{2,1,4,5,2,4,1}就会有这样的结果:

(2^1^4^5^2^4^1) => ((2^2)^(1^1)^(4^4)^(5)) => (0^0^0^5) => 5

reference:http://www.powerxing.com/leetcode-single-number/

 

解法二:hash map (reference: Clean Code Handbook)

we could use a map to keep track of the number of times an element apprears. In a second pass, we could extract the single number by consulting the hash map. As a hash map provides constant time lookup, the overall complexity is O(n), where n is the total number of elements. 

 

 

 1     public int singleNumber(int[] nums) 
 2     {
 3         //use hashmap
 4         Map<Integer,Integer> map = new HashMap<>();
 5         for(int x: nums)
 6         {
 7             int count=map.containsKey(x)?map.get(x):0;
 8             map.put(x,count+1);
 9         }
10         for(int x: nums)
11         {
12             if(map.get(x)==1)
13             {
14                 return x;
15             }
16         }
17     
18        throw new IllegalArgumentException("No Single Elment");
19 
20     }

 

 

解法三:Hash set (reference: clean code handbook)

Although the map approach works, we are not taking advantage of the "every elements apprears twice except one" property. Could we do better in one pass

How about inserting the elements into a set instead? If an element already exists, we discard the element from the set knowing that it will not appear again. After the first pass, the set mush contain only the single element. 

 1 public class Solution {
 2     public int singleNumber(int[] nums) {
 3         //use hashset
 4         HashSet<Integer> set = new HashSet<>();
 5         for(int x: nums)
 6         {
 7             if(set.contains(x))
 8             {
 9                 set.remove(x);
10             }
11             else
12             {
13                 set.add(x);
14             }
15         }
16         
17         return set.iterator().next();
18     }
19 }

 

set.iterator:

The following example shows the usage of java.util.HashSet.iterator()

 1 package com.tutorialspoint;
 2 
 3 import java.util.*;
 4 
 5 public class HashSetDemo {
 6    public static void main(String args[]) {
 7    // create hash set
 8    HashSet <String> newset = new HashSet <String>();
 9                   
10    // populate hash set
11    newset.add("Learning"); 
12    newset.add("Easy");
13    newset.add("Simply");  
14       
15    // create an iterator
16    Iterator iterator = newset.iterator(); 
17       
18    // check values
19    while (iterator.hasNext()){
20    System.out.println("Value: "+iterator.next() + " ");  
21    }
22    }    
23 }

Let us compile and run the above program, this will produce the following result.

Value: Learning 
Value: Simply 
Value: Easy

 

reference:

http://blog.csdn.net/kenden23/article/details/13625297

http://www.programcreek.com/2012/12/leetcode-solution-of-single-number-in-java/

http://www.tutorialspoint.com/java/util/hashset_iterator.htm 

posted @ 2015-07-29 23:44  Hygeia  阅读(200)  评论(0编辑  收藏  举报