尋找數組中唯一的數

題目: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?

翻譯:

一個數組中,除了一個數是唯一的,其他的數都存在2個,找出唯一的那個數.
要求:算法的時間複雜度爲線性的,並且不用額外的內存空間

答案:

public class Solution {
    public int singleNumber(int[] nums) {
        int rst = nums[0];
        int size = nums.length;
        for (int i = 1; i < size; i++) {
            rst = rst ^ nums[i];
        }
        return rst;
    }
}

性能排名

算法解釋:

利用了^異或運算符的特性,任何兩個相同數進行異或運算,結果都爲0,0和任何數的異或運算都爲那個數本身。由於當前數組中除了一個數是唯一的,其他的數都是成對存在的,因此,對所有的數進行異或運算之後的結果,就是那個唯一的數

發佈了54 篇原創文章 · 獲贊 16 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章