1. 程式人生 > >46. 主元素

46. 主元素

nbsp pos turn class i++ 之一 num .so 計算

題目:給定一個整型數組,找出主元素,它在數組中的出現次數嚴格大於數組元素個數的二分之一。

思路:題目中又說要嚴格大於數組個數的二分之一,所以先給數組先排序。如果存在的話那數組中間的那個數一定是主元素。所以只需要計算和中間元素相同的個數,然後判斷是否大於二分之一就可以了。

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;
}
}
}

46. 主元素