1. 程式人生 > >lintcode.46 主元素

lintcode.46 主元素

lec integer 空間復雜度 出現次數 else nbsp color dropbox aps

給定一個整型數組,找出主元素,它在數組中的出現次數嚴格大於數組元素個數的二分之一。

註意事項

You may assume that the array is non-empty and the majority number always exist in the array.

您在真實的面試中是否遇到過這個題? Yes 哪家公司問你的這個題? Airbnb Amazon LinkedIn Cryptic Studios Dropbox Apple Epic Systems TinyCo Yelp Hedvig Zenefits Uber Snapchat Yahoo Microsoft Bloomberg Facebook Google Twitter
感謝您的反饋 樣例

給出數組[1,1,1,1,2,2,2],返回 1

挑戰

要求時間復雜度為O(n),空間復雜度為O(1)

這道題要求O(n),肯定是遍歷一遍出結果。然而主元素一定大於長度的一半。由此,主元素減去其他所有數的數量還是會大於0。

class Solution {
public:
    /*
     * @param nums: a list of integers
     * @return: find a  majority number
     */
    int majorityNumber(vector<int> &nums) {
        // write your code here
        int s=nums.size();
        int res=nums[0];
        int cnt=1;
        for(int i =1;i<s;i++)
        {
            if(res==nums[i])
                cnt++;
            else
                cnt--;
            if(cnt<=0){
                res=nums[i];
                cnt=0;
            }
        }
        return res;
    }
};

  

lintcode.46 主元素