LintCode 主元素

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_30440627/article/details/54929925

给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。

样例

给出数组[1,1,1,1,2,2,2],返回 1

方法一:枚举法,时间复杂度O(n2)

依次比较每个数出现的次数,记下出现次数最多的值,如果出现次数大于个数的一半,返回它。

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: The majority number
     */
    int majorityNumber(vector<int> nums) {
        // write your code here
        int n = nums.size();
        int times1 = 0;
        int times2 = 0;
        int index =0;
        for(int i=0; i<n; i++)
        {
            for(int j=0; j<n; j++)
            {
                if(nums[i] == nums[j])
                    times1++;
            }
            if(times1 > times2)
            {
                times2 = times1;
                index = i;
            }
            times1 = 0;
        }
        if(times2 > n/2)
        {
            return nums[index];
        }
    }
};


方法二 :将数组进行排序,转化为有序序列,如果存在主元素,则一定是序列的中位数。

这样时间复杂度取决于排列方法 + 遍历判断次数是否大于一半。

时间复杂度:排列O(nlogn)+遍历O(n) = O(n)

代码略……



猜你喜欢

转载自blog.csdn.net/sinat_30440627/article/details/54929925