題目:
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;
}
}