[算法相關] 136. Single Number--取出非重複數字

 

136. 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?

 

Subscribe to see which companies asked this question

題意:給定一個數組,數組中除了一個元素,其他元素都有兩個。找到那個唯一的元素。

 

public class Solution {
    public int singleNumber(int[] nums) {
    HashSet<Integer> set = new HashSet<Integer>();
        for(int i = 0; i <nums.length; i++){
            if(!set.contains(nums[i])){
                set.add(nums[i]);
            }else{
                set.remove(nums[i]);
            }
        }
        int m =set.hashCode();
        return m;
    }
}
使用哈希表做出來的時候,哥哥是很高興的,但是看到有些人用到了位運算求解,發現世界真大……
int singleNumber(int A[], int n) {
    int result = 0;
    for (int i = 0; i<n; i++)
    {
        result ^=A[i];
    }
    return result;
}
簡直完美……

 

原文鏈接:https://leetcode.com/problems/single-number/

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章