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的元素,n为数组长度,并且题目假设数组不为空,且存在众数。
思路:本题的解题思路很多,可以直接利用HashMap进行统计,也可以先进行排序,然后遍历一遍记录出现次数最多的那个元素。本次使用排序方法解决问题。
代码:
public int majorityElement(int[] nums) { Arrays.sort(nums); //进行排序 int majority = nums[0],count= 1; for(int i = 1;i<nums.length;i++){ if(majority==nums[i]){ count+=1; if(count>(nums.length/2)) //判断是否为众数 { return majority; } }else{ majority = nums[i]; count=1; } } return majority; }
盗一张图LeetCode的建议解决方案:
时间: 2024-10-12 16:10:15