首页 > 其他 > 详细

【LeetCode从零单刷】Single Number II

时间:2015-05-13 12:55:03      阅读:194      评论:0      收藏:0      [点我收藏+]

题目:

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

解答:

如果是挑出非偶数次数的元素,可以利用每个元素依次异或的方法。但是非奇数次数(3,5,7,9……)的元素?

如果要快,可以hash_map存储。然后遍历一遍hash_map找到Single Number。

换种思路,按找不同的Single Number对应的位。细节上:

  1. bit = 1 << i; 然后利用当前数与 bit 位与,根据结果判断当前数的第 i 位是否有 1;
  2. 将最终的结果第 i 位置为 1,可以位或操作:ans | bit.
class Solution {
public:
    int singleNumber(int A[], int n) {
        int bit, bitsum;
        int ans;
        for(int i = 0; i < 32; i++)
        {
            bit = 1 << i;
            bitsum = 0;
            for(int j = 0; j < n; j++)
            {
                if(bit & A[j]) bitsum++; 
            }
            
            if(bitsum % 3)  ans = ans | bit;
        }
        return ans;
    }
};

【LeetCode从零单刷】Single Number II

原文:http://blog.csdn.net/ironyoung/article/details/45690459

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!