[LeetCode]:Single Number III

Describe
  Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

Input

nums = [1, 2, 1, 3, 2, 5]

Output

[3, 5]

Analyse
  自己寫的算法是用LinkedList來做的,然後一層循環,如果當前nums[i]在LinkedList裏面,那麼說明這個數是重複的,所以就將這個數從List裏面移除,反之就將數加入到List裏面,最後List裏面剩餘的就是那兩個只出現一次的數。(⊙v⊙)嗯,怎麼說呢,這是正常的邏輯,然後運行也通過了,然後一看時間是505ms,有點慢了,應該是java的原因吧,看看別人的時間吧,哦,2ms!!!

  我待算法如初戀,算法虐我千百遍!

Code
  自己的就不拿出來了,看看大神的吧%>_<%

public class Solution{
    public int[] singleNumber(int[] nums){
        int diff = 0;  
        for (int num : nums){  
            diff ^= num;  
        }  
        diff &= -diff;  
        int[] rets = {0, 0};
        for (int num : nums)  
        {  
            if ((num & diff) == 0) 
                rets[0] ^= num;  
            else 
                rets[1] ^= num;  
        }  
        return rets;  
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章