[Leetcode] #136#137#260 Single Number I & II & III

来源:互联网 发布:淘宝商场正品代购 编辑:程序博客网 时间:2024/04/29 04:17

Discription:

Given an array of integers, every element appears twice except for one. Find that single one.

Solution:

1.任何相同数异或等于0

2.0与任何数异或等于该数

3.异或的结合律

int singleNumber1(vector<int>& nums) {int res = 0;for (int i = 0; i < nums.size(); i++){res = res^nums[i];}return res;}

Discription:

Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

Solution:

把二进制中的每一位相加除3取余可以得到结果。

int singleNumber(vector<int>& nums) {int ans = 0;for (int i = 0; i < 32; i++) {int sum = 0;for (int j = 0; j < nums.size(); j++) {sum += (nums[j] >> i) & 1;}sum %= 3;ans |= sum << i;}return ans;}

Discription:

Given an array of numbers 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.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Solution:

根据Single Number I 思路,这里需要把原数组分成两个子数组,使得每个子数组包含一个只出现一次的数字,而其他数字都成对出现两次。

从头到尾异或数组中的每一个数字,那么最终的结果就是两个只出现一次的数字的异或结果。找到结果数字中第一个为1的位的位置,以这一位为标准把原数组中的数字分成两个子数组。

vector<int> singleNumber(vector<int>& nums) {int lastBit = 0, num1 = 0, num2 = 0;for (int num : nums)lastBit ^= num;lastBit = (lastBit&(lastBit - 1)) ^ lastBit;for (int num : nums){if (num & lastBit)num1 ^= num;elsenum2 ^= num;}return vector<int>{num1, num2};}

0 0
原创粉丝点击