zoukankan      html  css  js  c++  java
  • LeetCode137: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?

    解题思路:

    这题比Single Number稍难些,不能用异或解决,但排序和bitmap还是可以的,只是时间复杂度和空间复杂度要多些

    这里我用另一种方式实现,根据所给数组中元素的规律,可利用每一bit位上1的个数进行解决,直接看代码吧

    实现代码:

    #include <iostream>
    
    using namespace std;
    /*
    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?
    */
    class Solution {
    public:
        int singleNumber(int A[], int n) {
            int once = 0;
            for(int i = 0; i < 32; i++)
            {
                int one_num = 0;//bit为第i位1的个数 
                for(int j = 0; j < n; j++)
                    if((A[j] >> i) & 1 == 1)
                        one_num++;
                //因为数组中只有一个数出现一次,其他数都出现三次,
                //所以除非要找数的当前bit位为1,否则one_num为3的倍数 
                if(one_num % 3)
                    once += (1 << i);
    
            }
            return once;
            
        }
    };
    
    int main(void)
    {
        int arr[] = {2,4,5,5,4,1,2,4,2,5};
        int len = sizeof(arr) / sizeof(arr[0]);
        Solution solution;
        int once = solution.singleNumber(arr, len);
        cout<<once<<endl;
        return 0;
    }
  • 相关阅读:
    poj 3243 Clever Y(BabyStep GiantStep)
    poj 2417 Discrete Logging
    poj 3481 Double Queue
    hdu 4046 Panda
    hdu 2896 病毒侵袭
    poj 1442 Black Box
    hdu 2815 Mod Tree
    hdu 3065 病毒侵袭持续中
    hdu 1576 A/B
    所有控件
  • 原文地址:https://www.cnblogs.com/mickole/p/3673607.html
Copyright © 2011-2022 走看看