主元素

来源:互联网 发布:大数据技术与城市规划 编辑:程序博客网 时间:2024/05/16 19:57

问题描述:

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

注意事项

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

样例

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

解题思路:

与落单的数解题思路相似,不同的是要找从比较的数开始,第n/2个仍是该数。

代码:

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

感悟:

算明白相同的数的个数,开始多想了。

原创粉丝点击