46. 主元素

题目:给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。

思路:题目中又说要严格大于数组个数的二分之一,所以先给数组先排序。如果存在的话那数组中间的那个数一定是主元素。所以只需要计算和中间元素相同的个数,然后判断是否大于二分之一就可以了。

public class Solution {
/*
* @param nums: a list of integers
* @return: find a majority number
*/
public int majorityNumber(List<Integer> nums) {
// write your code here
int max=0;
int len = nums.size();
Collections.sort(nums);
int temp = nums.get(len/2);
for(int i = 0;i<len;i++){
if(temp == nums.get(i)){
max++;
}
}

if(max>len/2){
return temp;
}else{
return 0;
}
}
}

原文地址:https://www.cnblogs.com/Pjson/p/8424398.html