Monday, July 20, 2015

Leetcodes 136: Single Number (C++)

Problem:
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?


There are lots of way to implement this problem.
Here we provide a method with vector and sort. Maybe you can work it out with a better solution.



class Solution {
public:
       int singleNumber(vector<int>& nums) {
              vector<int> v_tmp = nums;
              sort(v_tmp.begin(), v_tmp.end());
              for (int i = 0; i<nums.size(); i++, i++){
                     if (v_tmp[i] != v_tmp[i + 1]){
                           return v_tmp[i];
                     }
              }
       }

};




A better way: 
Bitwise operation:
    //bitwise operation: XOR ^
    //As a^b^c^a^b^d^d
    //  =a^a^b^b^d^d^c
    //  =0^  0^  0  ^c
    //  =c

class Solution {
public:
    //bitwise operation: XOR ^
    //As a^b^c^a^b^d^d
    //  =a^a^b^b^d^d^c
    //  =0^  0^  0  ^c
    //  =c
    int singleNumber(vector<int>& nums) {
        if(nums.size()==0)return -1;
        int res=nums[0];
        for(int i=1;i<nums.size();i++){
            res=res^nums[i];
        }
        return res;
    }

};

No comments:

Post a Comment