1. 程式人生 > >查詢陣列中只出現一次的數(一)——Leetcode系列(十四)

查詢陣列中只出現一次的數(一)——Leetcode系列(十四)

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?

My Answer:

public class Solution {
    public int singleNumber(int[] A) {
        Set<Integer> set = new HashSet<Integer>();
        int length = A.length;
        for(int i = 0; i < length; i++){
            if(set.contains(A[i])){
                set.remove(new Integer(A[i]));
            }else{
                set.add(A[i]);
            }
        }
        Iterator<Integer> ite = set.iterator();
        return ite.next();
    }
}

題目來源:https://oj.leetcode.com/problems/single-number/