Leetcode Num.169 -- Majority Element

来源:互联网 发布:阿里云主机多少钱 编辑:程序博客网 时间:2024/05/06 19:04

题目描述:

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.
Credits:

解题思路:

要找出现次数大于⌊ n/2 ⌋的元素,很容易想到如果数组是有序的,直接取index为⌊ n/2 ⌋的元素便是。

Code:

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