【LeetCode题解】Single Number II

来源:互联网 发布:学西班牙语的软件 编辑:程序博客网 时间:2024/05/17 14:29

Single Number II

 (Java代码)

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 Solution {    public int singleNumber(int[] A) {int once =0;int twice=0;for(int i=0;i<A.length;i++){twice |= once & A[i];             once ^= A[i];//once记录了在A[i]之前出现的数位为1的情况。            int not_three = ~(once & twice);            once = not_three & once;            twice = not_three & twice;}return once;        }}
思路:这道题我想了很久,数位运算应该从整体考虑要,对于异或运算,要是总共有3个一样的数,进行3次,还是这个数本身,(我之前就是考虑太多每一步的结果)。

once里对3个一样的数进行异或(3次后还是它本身),twice里的数(当这个数第一次出现里面是0,第二次里面是这个数,第三次里面是这个数)。

当他俩一样的时候就把once和twice致零。

最后once里就是只出现一次的数。

原创粉丝点击