136. Single Number leetcode做題報告

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?

class Solution {

public:

    int singleNumber(vector<int>& nums) {

        for(int i=1;i<nums.size();i++){

            nums[0]^=nums[i];

        }

        return nums[0];

    }

};


要求O(n)並且不用額外的變量。
非常巧妙的技巧。相同數取異或爲0,所0和所有數的異或爲本身,所以最後剩下的就是Single Number。


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