题目来源:主元素
题目描述:
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
样例:
给出数组[1,1,1,1,2,2,2],返回 1
Java代码:
public int majorityNumber(ArrayList<Integer> nums) {
// write your code
int[] number= new int[2000];
int count = 0,mix=0,nowcount=1,nownumber=0;
while (count<nums.size()) {
number[count]=nums.get(count);
count++;
}
mix = count;
count--;
Arrays.sort(number,0,count);
for (int i = 1; i <= count; i++) {
nownumber = number[i];
if (number[i]!=number[i-1]) {
nowcount=1;
}else {
nowcount++;
}
if (nowcount>mix/2) {
break;
}
}
return nownumber;
}