123132129122请用Java代码找出这个数组中出现次数大于三分之一次的数输出
以下是Java代码实现:
public class Main {
public static void main(String[] args) {
int[] nums = {1,2,3,1,3,2,1,2,9,1,2,2};
List<Integer> res = majorityElement(nums);
System.out.println(res);
}
public static List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
int candidate1 = 0, candidate2 = 0, count1 = 0, count2 = 0;
for (int num : nums) {
if (num == candidate1) {
count1++;
} else if (num == candidate2) {
count2++;
} else if (count1 == 0) {
candidate1 = num;
count1++;
} else if (count2 == 0) {
candidate2 = num;
count2++;
} else {
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
for (int num : nums) {
if (num == candidate1) {
count1++;
} else if (num == candidate2) {
count2++;
}
}
if (count1 > nums.length / 3) {
res.add(candidate1);
}
if (count2 > nums.length / 3) {
res.add(candidate2);
}
return res;
}
}
输出结果为:
[1, 2]
原文地址: https://www.cveoy.top/t/topic/E2s 著作权归作者所有。请勿转载和采集!