LeetCode - 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?


思路與步驟:

極低效率思路:

用 HashMap

先排序

高效思路:

學習別人的思路

XOR,注意數組中用到抑或時常常會所有的數字一起抑或,因爲在數組中單獨兩個數字抑或意義不大。


編程實現:

這裏只給出用抑或實現的程序

public class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for (int n: nums)   result ^= n;
        return result;
    }
}



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