class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
if(nums.length == 1){
return nums[0];
}
for(int i = 0;i<nums.length-1;i++){
int count = 1;
for(int j = i+1;j<nums.length;j++){
if(nums[i] == nums[j]){
count++;
}
}
if(count>(nums.length/2)){
return nums[i];
}
}
return -1;
}
}
数组中占比超过一半的元素称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。
最新推荐文章于 2024-07-15 12:10:21 发布