给定一个非空的整数数组,每个数字都出现三次,只有一个数字例外只出现一次。找到那唯一的一个数字。
提示: 你的算法应当在线性时间复杂度内完成。你能不用额外空间来实现吗?
例一:
输入: [2,2,3,2]
输出: 3
例二:
输入: [0,1,0,1,0,1,99]
输出: 99
/*
* 137. Single Number II
* https://leetcode.com/problems/single-number-ii/
* https://www.whosneo.com/137-single-number-ii/
*/
public class SingleNumberII {
public static void main(String[] args) {
SingleNumberII solution = new SingleNumberII();
int[] nums;
nums = new int[]{2, 2, 3, 2};
System.out.println(solution.singleNumber(nums));
nums = new int[]{0, 1, 0, 1, 0, 1, 99};
System.out.println(solution.singleNumber(nums));
}
public int singleNumber(int[] nums) {
int seen1 = 0;
int seen2 = 0;
for (int num : nums) {
seen1 = ~seen2 & (seen1 ^ num);
seen2 = ~seen1 & (seen2 ^ num);
}
return seen1;
}
}
参考链接:https://leetcode-cn.com/problems/single-number-ii/solution/single-number-ii-mo-ni-san-jin-zhi-fa-by-jin407891/