[LeetCode169]Majority Element
Majority Element
Total Accepted: 58500 Total Submissions: 163658My Submissions
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.
题意为:找出最多的数是哪个数。
package com.leetcode.mair;
import java.util.Arrays;
public class Solution169 {
public int majorityElement(int[] nums) {
int mel = nums.length/2,count=1,me=1;
Arrays.sort(nums);
me=nums[0];
for(int i=1; i<nums.length; i++){
if(nums[i-1] == nums[i]){
count++;
if(count>=mel){
me = nums[i];
mel = count;
}
}else
count=1;
}
return me;
}
public static void main(String[] args) {
int nums[]= {1};
System.out.println(new Solution169().majorityElement(nums));
}
}

浙公网安备 33010602011771号