LeetCode137:Single Number II

mickole發表於2014-02-18

題目:

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;
}

相關文章