Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. int singleNumber(vector<int>& nums) {
  2. if (nums.size() == 1) return nums[0]; // If there is one value, return it.
  3.  
  4. sort(nums.begin(), nums.end()); // Sort the vector, groups of three will appear beside each other
  5.  
  6. int res{}; // Stores result
  7.  
  8. for (int i{2}; i < nums.size(); i += 3) { // Progress in groups of three.
  9. if (nums[i]^nums[i-1]^nums[i-2] != nums[i]) { // Check the previous three elements. If they don't XOR to one of the elements
  10. if (nums[i]^nums[i-1] == 0) { // then our single element is hidden in one of these three.
  11. res = nums[i-2]; // Check them individually. If two XOR to 0, the third one is out of place
  12. break; // Important - break when you found it!
  13. }
  14. if (nums[i]^nums[i-2] == 0) {
  15. res = nums[i-1];
  16. break;
  17. }
  18. if (nums[i-i]^nums[i-2] == 0) {
  19. res = nums[i];
  20. break;
  21. }
  22. }
  23. if (i + 3 > nums.size()) return res = nums[nums.size()-1]; // Edge casae where single element is the last element.
  24. } // It is the last element if we still don't have a solution and
  25. // we have processed the last group of three elements.
  26. return res;
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement