Ai
1 Star 0 Fork 0

徐长贺/Leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
_137.java 1.19 KB
一键复制 编辑 原始数据 按行查看 历史
Steve Sun 提交于 2018-04-26 23:37 +08:00 . refactor 137
package com.fishercoder.solutions;
import java.util.HashMap;
import java.util.Map;
/**
* 137. Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
*/
public class _137 {
public static class Solution1 {
public int singleNumber(int[] nums) {
Map<Integer, Integer> map = new HashMap();
for (int i : nums) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
for (int key : map.keySet()) {
if (map.get(key) != 3) {
return key;
}
}
return 0;
}
}
public static class Solution2 {
/** Credit: https://discuss.leetcode.com/topic/11877/detailed-explanation-and-generalization-of-the-bitwise-operation-method-for-single-numbers/2 */
public int singleNumber(int[] nums) {
int counter1 = 0;
int counter2 = 0;
int mask = 0;
for (int num : nums) {
counter2 ^= counter1 & num;
counter1 ^= num;
mask = ~(counter1 & counter2);
counter1 &= mask;
counter2 &= mask;
}
return counter1;
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/isulong/Leetcode.git
git@gitee.com:isulong/Leetcode.git
isulong
Leetcode
Leetcode
master

搜索帮助