可以使用哈希表来实现。具体步骤如下:
以下是一个示例代码:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static int findMostFrequentNumber(int[] nums) {
Map<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : nums) {
if (frequencyMap.containsKey(num)) {
frequencyMap.put(num, frequencyMap.get(num) + 1);
} else {
frequencyMap.put(num, 1);
}
}
int mostFrequentNumber = 0;
int maxFrequency = 0;
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
int num = entry.getKey();
int frequency = entry.getValue();
if (frequency > maxFrequency) {
mostFrequentNumber = num;
maxFrequency = frequency;
}
}
return mostFrequentNumber;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 2, 2, 3, 3, 3};
int mostFrequentNumber = findMostFrequentNumber(nums);
System.out.println("Most frequent number: " + mostFrequentNumber);
}
}
这个方法的时间复杂度为O(n),其中n是整数数组的长度。
领取专属 10元无门槛券
手把手带您无忧上云