2015年8月6日 星期四

LEET code--Single Number

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?

最快想試用兩個for 暴力算

但是要線性又不要求多餘空間
就很難阿

看到有人用XOR  真是天才
因為兩個依樣數字就會剛好抵銷


numsSize>1 是因為 用了nums[0]  要把0給跳過
------------
int singleNumber(int* nums, int numsSize) {
    while(numsSize>1){
        nums[0]^=nums[--numsSize];
    }
    return nums[0];
}

沒有留言:

張貼留言