leetcode

Leetcode submissions
git clone git://git.laack.co/leetcode.git
Log | Files | Refs | README

single-numberV2.cpp (933B)


      1 #include <iostream>
      2 #include <vector>
      3 #include <unordered_map>
      4 #include <algorithm>
      5 using namespace std;
      6 
      7 
      8 // Time:    Memory:
      9 // 20ms     16.9MB
     10 // 64.90%   57.10%
     11 // This is faster than using a map because the map requires a lot of checks
     12 // to see if the map already has a value in it. Then it needs to iterate through the list
     13 // again to find which value did not have a pairing.
     14 
     15 //Another solution that involves sorting the list and then checking to
     16 //see if the next value in the list is equal to the current value.
     17     int singleNumber(vector<int>& nums) {
     18         sort(nums.begin(), nums.end());
     19         for(int i = 0 ; i < nums.size() - 1 ; i += 2){
     20             if(nums[i] != nums[i + 1]){
     21                 return nums[i];
     22             }
     23         }
     24         return nums[nums.size() - 1];
     25     }
     26 
     27 
     28 int main(){
     29     //Ans should be 4
     30     vector <int> vec = {0 , 10, 0, 10, 2, 2, 3, 4, 3};
     31     cout << singleNumber(vec) << endl;
     32 
     33 }