【LeetCode】137. Single Number II 只出现一次的数字 II(Medium)(JAVA)
题目地址: https://leetcode.com/problems/single-number-ii/
题目描述:
Given a non-empty 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?
Example 1:
Input: [2,2,3,2]
Output: 3
Example 2:
Input: [0,1,0,1,0,1,99]
Output: 99
题目大意
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现了三次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
解题方法
- 这一题和在两次中找单独出现一次的问题类似,但是这次是在三次中找单独出现一次的元素,两次中找单独出现一次的方法就不好用了(因为异或都会存在)
- 采用类似的方法,既然一次异或不好用,我们就把结果存到两位里面即:00, 01, 10, 00 分别表示出现零次,一次,两次,三次的情况
- 列出所有的情况: 00 + 0 = 00, 00 + 1 = 01, 01 + 0 = 01, 01 + 1 = 10, 10 + 0 = 10, 10 + 1 = 00
- 用高为 second 表示高位, first 表示低位,然后找出表达式
if second = 1
first = 0
if second = 0
if n = 0
first = first
if n = 1
first = ~first
- 简化一下
if second = 1
first = 0
if second = 0
first = first ^ n
- 再简化: first = fisrt ^ n & ~second
- 同理得出: second = second ^ nums[i] & ~first
class Solution {
public int singleNumber(int[] nums) {
int first = 0;
int second = 0;
for (int i = 0; i < nums.length; i++) {
first = first ^ nums[i] & ~second;
second = second ^ nums[i] & ~first;
}
return first;
}
}
执行耗时:1 ms,击败了76.67% 的Java用户
内存消耗:38.5 MB,击败了58.28% 的Java用户
![](https://i-blog.csdnimg.cn/blog_migrate/6c56d31f951aece27c5faae608dfac2e.jpeg#pic_center)