leetcode137. Single Number II

来源:互联网 发布:淘宝店 售后率 编辑:程序博客网 时间:2024/05/10 12:18

链接:https://leetcode.com/problems/single-number-ii/
题目:
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?

Subscribe to see which companies asked this question
题目大意:给你一个数组,每个元素出现三次,但是只有一个不是三次,喊你找出那一个。
思路:我们这里一样可以看作每个数字都是由32位二进制组成,每一位上面的数字出现的次数要么可以和3取余,要么不行。我们把不行的使用或运算。代码如下:

public class Solution {    public int singleNumber(int[] nums) {        int length=nums.length;        int res=0;        for(int i=0;i<32;i++){            int count=0;            int mask=1<<i;            for(int j=0;j<length;j++){                if((nums[j]&mask)!=0)                    count++;            }            if(count%3!=0)                res|=mask;        }        return res;    }}
0 0
原创粉丝点击