2015年7月23日 星期四

LeetCode:Single Number

題目:

Given an array of integers, every element appears twice except for one. Find that single one.

一串整數數列,找出只出現一次的數字。



想法:

XOR的經典題,還能應用在swap函數,不用額外儲存空間
C#:
  1. public void swap(int a , int b){
  2. a^=b;
  3. b^=a;
  4. a^=b;
  5. }
因為a^a=0 (a^b)^a=b的關係使然


Accepted Solution:


C#


  1. public class Solution {
  2. public int SingleNumber(int[] nums) {
  3. int ans = 0;
  4. foreach (int i in nums){
  5. ans^=i;
  6. }
  7. return ans;
  8. }
  9. }

沒有留言:

張貼留言