136 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?

  #include <iostream>
  #include <vector>
  #include <algorithm>
  using namespace std;


  int singleNumber(vector<int>& nums) {
      sort(nums.begin(), nums.end());

      for (int i = 0; i < nums.size(); i+=2)
      {
          try
          {
              if (nums.at(i) == nums.at(i + 1))
                  continue;
              else return nums.at(i);
          }
          // element (i+1) appeared to be at the last position
          catch (const std::out_of_range& oor)
          {
              //std::cerr << "Out of Range error: " << oor.what() << '\n';
              return nums.at(i);
          }
      }
  }

  int main()
  {
      vector<int> myvect{ 2,2,1 };
      cout << singleNumber(myvect);
  }
  • Attempt 2: The above is terrible implementation, and certainly not linear.

    • The trick here is identifying that when we have the same number twice, and xor will reset that particular bit to zero. Anything that xors with zero will return back the original number. Regardless of the combination of bits that come in, the individual bits will become flipped when it repeats.

int singleNumber(vector<int>& nums) {
    int sum = 0;
    for (auto i : nums) {
        sum ^= i;
    }
    return sum;
}

Last updated