Middle-题目11:137. Single Number II

原创 2016年05月31日 15:31:04

题目原文:
Given an array of integers, every element appears three times except for one. Find that single one.
题目大意:
给出一个数组,除了一个元素出现了一次外都出现了三次,找出这个单独的元素。
题目分析:
1. 朴素解法:这回使用HashMap统计每个元素出现次数,然后返回那个次数为1的。
2. 位运算解法:(参考higerzhang大神的博客)遍历32次每次记录某位的出现的次数,如果不能被三整除,说明那个出现一次的就在该位有值,那么ans 或该位一下就可以了。
源码:(language:java/c)
1. 朴素解法:

public class Solution {
    public int singleNumber(int[] nums) {
        HashMap<Integer,Integer> count=new HashMap<Integer,Integer>();
        for(int num:nums) {
            if(count.containsKey(num))
                count.put(num, count.get(num)+1);
            else
                count.put(num, 1);
        }
        for(Integer key:count.keySet())
            if(count.get(key)==1)
                return key;
        return 0;         
    }
}
  1. 位运算解法:
int singleNumber(int nums[], int numsSize) {
    int single = 0;
    for (int i = 0; i < 32; i++) {
        int cnt = 0, bit = 1 << i;
        for (int j = 0; j < numsSize; j++)
            if (nums[j] & bit) cnt++;
        if (cnt % 3 != 0)
            single |= bit;
    }
    return single;
}

成绩:
朴素解法:15ms,beats 10.87%,众数1ms,23.02%
位运算解法:12ms,beats 8.33%,众数8ms,48.61%
Cmershen的碎碎念:
HigherZhang的博客中还提到了第三种算法,我理解能力有限,一时间未能完全看明白,以后可以点击上面的链接再研究一番。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

LeetCode(137) Single Number II

题目Given an array of integers, every element appears three times except for one. Find that single one...

【LeetCode】137. Single Number II

137. Single Number II Given an array of integers, every element appears three times except for one...

137. Single Number II

Given an array of integers, every element appears three times except for one. Find that single one. ...

Leetcode 137. Single Number II

题意:给定一个数组,已知这个数组中有一个数出现了一次,其它数都出现三次。找出这个数 解法: 有个很好理解的解法,因为int有32位,所以开一个数组bit[32],遍历32次,把每个位出现的次数分别...

137. Single Number II

Given an array of integers, every element appears three times except for one. Find that single one. ...

leetcode[137]:Single Number II

Single Number IIGiven an array of integers, every element appears three times except for one. Find t...

Leetcode 137 Single Number II 仅出现一次的数字

给出一个整数数组,除了某个元素外所有元素都出现三次。找出仅出现一次的数字。

leetcode-137 Single Number II

思路一: 对于除出现一次之外的所有的整数,其二进制表示中每一位1出现的次数是3的整数倍,将所有这些1清零,剩下的就是最终的数。用ones记录到当前计算的变量为止,二进制1出现“1次”(mod 3...

<LeetCode OJ> 136 / 137 / 260 Single Number(I / II / III)

260. Single Number III My Submissions Question Total Accepted: 19802 Total Submissions: 47891 Di...

leetcode137 Single Number II

题目: Given an array of integers, every element appears three times except for one. Find that single...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)