class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
return nums[nums.size() / 2];
}
};
This problem have a cheat.^_^
The problem assumes that the array is non-empty and the majority element always exist in the array.So we can have a cheat, if consider the condition dosen't satisfy.We should traverse the array,and then make a decision.
While this problem might have a "cheat" I would challenge you to see if you can improve your runtime analysis from an assumed O(n log n) to something better. I would venture to say that just because it can be done simply in two lines doesn't mean that you have found the most efficient answer.
@k_master_2015 @dada0z @includecmath
Don`t you think this is a good idea? Although the test data is not have [1,1,2,3]
@dada0z Majority element is the element that appears more than ⌊ n/2 ⌋ times, so the array [1,1,2,3] is not valid. It should be [1,1,1,2,3], and then this function will work well.