題目:
Given an array of integers, every element appears twice except for one. Find that single one.一串整數數列,找出只出現一次的數字。
想法:
XOR的經典題,還能應用在swap函數,不用額外儲存空間C#:
public void swap(int a , int b){
a^=b;
b^=a;
a^=b;
}
因為a^a=0 (a^b)^a=b的關係使然Accepted Solution:
C#
public class Solution {
public int SingleNumber(int[] nums) {
int ans = 0;
foreach (int i in nums){
ans^=i;
}
return ans;
}
}
沒有留言:
張貼留言