LeetCode
来源:互联网 发布:python 复杂网络 编辑:程序博客网 时间:2024/06/05 20:20
Given an 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?
不得不说,位运算真的是神奇方便快捷,感觉如果精通位运算,很多问题都不是问题哎
思路:所有的数都出现过三次,那每一位上加起来一定模3为0,若不为0,那就是只出现过一次的那个数咯
时间复杂度O(32n),空间O(1)
class Solution {public: 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) { if ((nums[j]>>i) & 1 == 1) { sum++; sum %= 3; } } if (sum) ans += sum << i; } return ans; }};
评论区有大神写了个写法,没看懂,先码一下
public int singleNumber(int[] A) { int ones = 0, twos = 0; for(int i = 0; i < A.length; i++){ ones = (ones ^ A[i]) & ~twos; twos = (twos ^ A[i]) & ~ones; } return ones;}
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- iOS10跳转系统设置方法
- $ git push warning: push.default 尚未设置,它的默认值在 Git 2.0 已从 'matching' 变更为 'simple'。若要不再显示本信息并保持传统习惯,进行如
- 示例一个PLSQL完成功能来说明PLSQL的作用(定义变量+异常处理+抛异常)
- 微信小程序之https步骤二
- JPA @MappedSuperclass 注解说明
- LeetCode
- iOS开发遇到的未解决问题
- 你不知道的JavaScript(二)变量提升
- POJ 3728 The merchant
- apache配置https协议常见问题解析
- 涂端
- javacript和java字符串长度控制
- ZOJ3430-AC自动机
- vue.js的devtools安装