首页 > 代码库 > Single Number

Single Number

https://oj.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?

public class Solution {    public int singleNumber(int[] A) {        int number = 0;        HashMap<Integer, Integer> map = new HashMap();        for (int i = 0; i < A.length; i++) {            if (map.get(A[i]) == null || map.get(A[i]) == 0) {                map.put(A[i], 1);            } else if (map.get(A[i]) == 1) {                map.put(A[i], 2);            }        }        Iterator<Integer> it = map.keySet().iterator();        while (it.hasNext()) {            Integer keyString = it.next();            if (map.get(keyString) == 1)                return keyString;        }        return number;    }}

1. 最复杂的方法是,两次遍历,时间复杂度O(n^2)。

2. 上面的解法是,放入map,每次放入时候判断get是不是已经有了,有了就值为2。最后取出value为1的。时间复杂度为O(n)。

3. 还有一个很tricky的解法。用异或的方法。思路就是每位bit出现2次就清零,所以可以不断异或运算得出最终结果。

public class Solution {    public int singleNumber(int[] A) {        int result = 0;        for(int i = 0; i < A.length; i++){            result = result ^ A[i];        }        return result;    }}

 

Single Number