?LeetCode刷題實(shí)戰(zhàn)260:只出現(xiàn)一次的數(shù)字 III
Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.
Follow up: Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
示例
示例 1:
輸入:nums = [1,2,1,3,2,5]
輸出:[3,5]
解釋:[5, 3] 也是有效的答案。
示例 2:
輸入:nums = [-1,0]
輸出:[-1,0]
示例 3:
輸入:nums = [0,1]
輸出:[1,0]
解題
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
vector<int> res(2, 0); // 分為兩組
int sum = 0; // sum是nums所有元素異或的結(jié)果
for(int i = 0; i < nums.size(); ++i) {
sum ^= nums[i];
}
int firstOne = sum & (-sum); // 得到最低位的1,sum & (-sum)這是一個(gè)常見的技巧
for(int i = 0; i < nums.size(); ++i) {
if(firstOne & nums[i]) { // 如果和firstOne相與為1,分到第一組(并且第一組所有元素進(jìn)行異或操作)
res[0] ^= nums[i];
} else { // 否則到第二組(并且第二組所有元素進(jìn)行異或操作)
res[1] ^= nums[i];
}
}
return res;
}
};
LeetCode刷題實(shí)戰(zhàn)258:各位相加
LeetCode刷題實(shí)戰(zhàn)259:較小的三數(shù)之和
