137:只出现一次的数字 II(增加新方式)

This commit is contained in:
huangge1199 2021-04-30 08:58:14 +08:00
parent abcdc53e3a
commit fd5f5a7dd9
2 changed files with 20 additions and 13 deletions

View File

@ -40,27 +40,34 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
//137:只出现一次的数字 II //137:只出现一次的数字 II
public class SingleNumberIi{ public class SingleNumberIi {
public static void main(String[] args) { public static void main(String[] args) {
//测试代码 //测试代码
Solution solution = new SingleNumberIi().new Solution(); Solution solution = new SingleNumberIi().new Solution();
} }
//力扣代码 //力扣代码
//leetcode submit region begin(Prohibit modification and deletion) //leetcode submit region begin(Prohibit modification and deletion)
class Solution { class Solution {
public int singleNumber(int[] nums) { public int singleNumber(int[] nums) {
Map<Integer,Integer> map = new HashMap<>(); // Map<Integer, Integer> map = new HashMap<>();
for (int num :nums){ // for (int num : nums) {
map.put(num,map.getOrDefault(num,0)+1); // map.put(num, map.getOrDefault(num, 0) + 1);
// }
// for (int num : map.keySet()) {
// if (map.get(num) == 1) {
// return num;
// }
// }
// return 0;
int ones = 0, twos = 0;
for(int num : nums){
ones = ones ^ num & ~twos;
twos = twos ^ num & ~ones;
} }
for (int num:map.keySet()){ return ones;
if(map.get(num)==1){
return num;
} }
} }
return 0;
}
}
//leetcode submit region end(Prohibit modification and deletion) //leetcode submit region end(Prohibit modification and deletion)
} }

File diff suppressed because one or more lines are too long