贪心算法Lintcode 46. Majority Element

46. Majority Element

Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.

Example

Given [1, 1, 1, 1, 2, 2, 2], return 1

Challenge

O(n) time and O(1) extra space

方法1:直接排序找中位数就可以

class Solution {
public:
    /*
     * @param nums: a list of integers
     * @return: find a  majority number
     */
    int majorityNumber(vector<int> &nums) {
        // write your code here
      sort(nums.begin(),nums.end());
      int numSize = nums.size();
      return nums.at(numSize/2);
    }
};

猜你喜欢

转载自blog.csdn.net/gulaixiangjuejue/article/details/80570327