137. 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

难度: medium

题目:
给定一个非空整数数组,其中一个元素出现一次,其它元素出现三次。找出有且仅出现一次的那个元素。
注意:你的算法时间复杂度为O(n)。能否实现它不使用额外的内存?

思路:
按位统计各个元素中位出现的次数,因为除1次出现的元素之外,其它元素都出现3次,因此按位统计位1和位0的个数应为3的倍数。最后只出现1次的那个元素的所有位都会剩下来。

Runtime: 3 ms, faster than 60.00% of Java online submissions for Single Number II.

class Solution {
    public int singleNumber(int[] nums) {
        int result = 0, bit = 0;
        for (int i = 0; i < 32; i++, bit = 0) {
            for (int j = 0; j < nums.length; j++) {
                bit += (nums[j] >> i) & 1;
                bit %= 3;
            }
            
            result |= (bit << i);
        }
        
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值