2.1.24 Single Number II

来源:互联网 发布:网络黄金裴雷和刘宁 编辑:程序博客网 时间:2024/05/17 11:06

Link: https://oj.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?

我的思路:remember 应该用位操作。对于出现三次的元素,对应的位一定出现3次(还是3的倍数?)。每一位对3取余,不为0的位组合起来就是只出现1次的数。

但我不知道通过什么操作才能把一个数表示成二进制。//(A[j]>>i) & 1

Note: 没法下笔。再做。

Time: O(n), Space: O(1) (O(32)

public class Solution {    public int singleNumber(int[] A) {        int[] count = new int[32];//store the total # of ones on each digit        for(int i = 0; i < 32; i++){//for each digit            for(int j = 0; j < A.length; j++){                count[i] += (A[j]>>i) & 1;            }        }        int result = 0;        for(int i = 0; i < 32; i++){            result += (count[i] %3) <<i;//can also use "|="        }        return result;    }}


0 0
原创粉丝点击