java在数组中查找多数数
这个问题以前有人问过。然而,我只想知道我的代码出了什么问题。它通过了大多数测试用例,但并不是所有的测试都通过了
给定一个整数数组,多数数是数组大小一半以上的数。找到它
public class Solution {
/**
* @param nums: a list of integers
* @return: find a majority number
*/
public int majorityNumber(ArrayList<Integer> nums) {
// write your code
Collections.sort(nums);
int j = 0, count = 0, out = 0, size = nums.size();
for(int i = 0; i < size; i++) {
if(nums.get(j) == nums.get(i)) {
count++;
if(count > size/2){
out = nums.get(i);
}
} else {
count = 1;
j = i;
}
}
return out;
}
}
编辑
我将代码更改为j=I&;根据答案,计数=1
例如,对于输入[1,1,1,2,2,2],输出应为2。 我的代码在这种情况下有效。它在大型输入情况下不起作用
我不想要其他解决方案,因为我已经在其他网站上找到了许多O(n)解决方案。我只想修正我自己的代码,知道我做错了什么
# 1 楼答案
在你的else区块中: