LeetCode-137. Single Number II

网友投稿 426 2022-08-29

LeetCode-137. Single Number II

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

Note:

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,3,2]Output: 3

Example 2:

Input: [0,1,0,1,0,1,99]Output: 99

题解:

计算一个int类型中每个比特位出现的次数,如果不是3的倍数,那么就是单独出现的数字提供的。

最后把不是3倍数的位或运算求出即可(不可用pow(2, i),有负数)

class Solution {public: int singleNumber(vector& nums) { int res = 0; int n = nums.size(); vector bits(32, 0); if (n == 0) { return -1; } for (int i = 0; i < n; i++) { for (int j = 0; j < 32; j++) { if ((nums[i] & (1 << j)) != 0) { bits[j]++; } } } for (int i = 0; i < 32; i++) { if (bits[i] % 3 != 0) { res |= (1 << i); } } return res; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:LeetCode-120. Triangle
下一篇:漠河火了!网红时代,如何解“目的地营销”这道题?
相关文章

 发表评论

暂时没有评论,来抢沙发吧~