136. 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?
class Solution { public: int singleNumber(vector<int>& nums) { sort(nums.begin(), nums.end()); vector<int>::size_type i; for(i = 0; i < nums.size() - 2; i += 2) { if(nums[i] != nums[i + 1]) { break; } } return nums[i]; } };排序可以过,但是不满足时间复杂度O(n)的条件
讨论区一个很巧妙的算法,利用亦或
https://discuss.leetcode.com/topic/1916/my-o-n-solution-using-xor
^ 按位异或 若参加运算的两个二进制位值相同则为0,否则为1
对于如下:
int x = 5;
int y = 0;
cout << (x ^ y);//5
y = 5;
cout << (x ^ y);//0
题外话:利用亦或,不用第三个变量交换两个数。
int main() { int x = 10; int y = 100; cout << "x = " << x << ";y = " << y << endl; x = x ^ y; y = x ^ y; x = x ^ y; cout << "x = " << x << ";y = " << y << endl; return 0; }即:
x = x ^ y;
y = x ^ y = x ^ y ^ y = x;
x = x ^ y = x ^ y ^ x = y;
#include <iostream> #include <vector> #include <set> #include <algorithm> using namespace std; class Solution { public: int singleNumber(vector<int>& nums) { int result = 0; for (auto iter = nums.begin(); iter != nums.end(); iter++) { result ^= *iter; } return result; } }; int main() { Solution s; vector<int>vec{1,2,3,3,5,2,1,4,4}; cout << s.singleNumber(vec); return 0; }
相同的题:
389. Find the Difference
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input: s = "abcd" t = "abcde" Output: e Explanation: 'e' is the letter that was added.
class Solution { public: char findTheDifference(string s, string t) { char ch = 0; for (string::size_type i = 0; i < s.size(); ++i) { ch ^= s[i]; } for (string::size_type i = 0; i < t.size(); ++i) { ch ^= t[i]; } return ch; } };
Keep it simple!