169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

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

//这里用一个比较巧的办法,如果出现次数大于 n/2 那么一定在 sort 之后最中间的一个数字就是我们要找的“主要数字”

public class Solution {
    public int majorityElement(int[] nums) {
        if(nums.length == 1){
            return nums[0];
        }
        Arrays.sort(nums);
        return(nums[nums.length/2]);
        
    }
}

留下评论