LeetCode 136. Single Number

原题链接在这里:https://leetcode.com/problems/single-number/

题目:

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?

题解:

首先会想到HashMap,HashSet的想法,但会用到extra O(n) space.

所以就要用到bit manipulation,这里和Single Number II非常相似, 32位的int, 每一位的count若是出现奇数,那么这一位就是用来组成single number的.

但这里有个更快的方法,就是用异或 ^ operator. 异或 every number in the array and the result would be the single number.

Method 1 Time Complexity: O(n). Space: O(n).

Method 2 Time Complexity: O(n). Space: O(1).

Method 3 Time Complexity: O(n). Space: O(1).

AC Java:

 1 public class Solution {
 2     public int singleNumber(int[] nums) {
 3         /*Method 1
 4         if(nums == null || nums.length == 0)
 5             return Integer.MIN_VALUE;
 6         
 7         HashSet hs = new HashSet();
 8         for(int i = 0; i < nums.length; i++){
 9             if(!hs.contains(nums[i])){
10                 hs.add(nums[i]);
11             }else{
12                 hs.remove(nums[i]);
13             }
14         }
15         
16         Iterator it = hs.iterator();
17         int res = Integer.MIN_VALUE;
18         while(it.hasNext()){
19             res = (int)it.next();
20         }
21         
22         return res;
23         */
24         
25         /*Method 2
26         if(nums == null || nums.length == 0)
27             return Integer.MIN_VALUE;
28             
29         int [] bitCounter = new int[32];
30         for(int i = 0; i<32; i++){
31             for(int j = 0; j<nums.length; j++){
32                 bitCounter[i] += (nums[j]>>i&1); //error
33             }
34         }
35         int res = 0;
36         for(int i = 0; i<32; i++){
37             res += (bitCounter[i]%2)<<i;
38         }
39         return res;
40         */
41         
42         //Method 3
43         if(nums == null || nums.length == 0)
44             return Integer.MIN_VALUE;
45         int res = 0;
46         for(int j = 0; j < nums.length; j++){
47             res = res ^ nums[j];
48         }
49         return res;
50     }
51 }

跟上Single Number IISingle Number III.

posted @ 2015-08-06 08:58  Dylan_Java_NYC  阅读(247)  评论(0编辑  收藏  举报