首页 > 代码库 > 只出现一次的数
只出现一次的数
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]
class Solution {public:vector<int> singleNumber(vector<int>& nums) { int x_xor_y = 0; for (int n: nums) { x_xor_y ^= n; } // 找到最后一位1 // 出现1表示,这一点处两个数的值不一样,一个为0一个为1,不然不可能异或出现1 int mask = x_xor_y & ~(x_xor_y - 1); int x = 0; int y = 0; // x: XOR of a,a,b,b,x // y: XOR of c,c,y for (int n: nums) { if (n & mask) { x ^= n; } else { y ^= n; } } return vector<int> {x, y};}};
Given an array of integers, every element appears twice except for one. Find that single one.
class Solution {public: int singleNumber(int A[], int n) { int num = 0; for (size_t i = 0; i < n; ++i){ num ^= A[i]; } return num; }};
Given an array of integers, every element appears three times except for one. Find that single one.
int singleNumber(vector<int> AA) { int ones = 0, twos = 0; //int size = sizeof(AA) / sizeof(int); for (int i = 0; i < AA.size(); i++){ ones = (ones ^ AA[i]) & ~twos; twos = (twos ^ AA[i]) & ~ones; } return ones;}
只出现一次的数
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。