1 题目
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,3,2]
输出: 3
示例 2:
输入: [0,1,0,1,0,1,99]
输出: 99
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/single-number-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2 Java
2.1 !方法一(HashSet)
由于其它元素出现了三次,不能通过将碰到第二次的元素从set中删除以获得仅出现一次的元素
通过元素总和sumArray、非重元素总和sumSet,来计算出仅出现一次的元素值
class Solution {
public int singleNumber(int[] nums) {
HashSet<Long> set = new HashSet<>();
long sumArray = 0, sumSet = 0;
for(long num: nums){
set.add(num);
sumArray += num;
}
for(long s: set) sumSet += s;
return (int)((3 * sumSet - sumArray) / 2);
}
}
2.2 方法二(HashMap)
class Solution {
public int singleNumber(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
// 该元素已出现过,value=1
if(map.containsKey(nums[i])) map.put(nums[i], 1);
// 该元素未出现过,value = 0
else map.put(nums[i], 0);
}
// 遍历map,找到出现一次的元素(value == 0)
// for(int key: map.keySet()){
// if(map.get(key) == 0) return key;
// }
for(Map.Entry<Integer, Integer> entry: map.entrySet()){
if(entry.getValue() == 0) return entry.getKey();
}
return -1;
}
}
2.3 !方法三(位运算)
第一次出现,seenOnce保存,seenTwice没有
第二次出现,seenOnce没有,seenTwice保存
第三次出现,都没有
class Solution {
public int singleNumber(int[] nums) {
int seenOnce = 0, seenTwice = 0;
for(int num: nums){
seenOnce = (~seenTwice) & (seenOnce^num);
seenTwice = (~seenOnce) & (seenTwice^num);
}
return seenOnce;
}
}