2023年1月13日 星期五

169. Majority Element

解題思路

題目敘述都直接提到 "The majority element is the element that appears more than ⌊n / 2⌋ times." 了,可知占多數的 element 一定超過一半,那找一半的位子是甚麼數就好。

程式碼

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        return nums[nums.size() / 2];
    }
};

沒有留言:

張貼留言