多數(shù)元素
給定一個大小為 n 的數(shù)組 nums ,返回其中的多數(shù)元素。多數(shù)元素是指在數(shù)組中出現(xiàn)次數(shù) 大于 ? n/2 ? 的元素。
你可以假設(shè)數(shù)組是非空的,并且給定的數(shù)組總是存在多數(shù)元素。
示例 1:
輸入:nums = [3,2,3]
輸出:3
示例 2:
輸入:nums = [2,2,1,1,1,2,2]
輸出:2
進(jìn)階:嘗試設(shè)計時間復(fù)雜度為 O(n)、空間復(fù)雜度為 O(1) 的算法解決此問題。
方法一:哈希表
class Solution {
public int majorityElement(int[] nums) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
if (map.containsKey(num)) {
map.put(num, map.get(num) + 1);
} else {
map.put(num, 1);
}
}
int max = 0;
int res = 0;
for (Map.Entry<Integer, Integer> integerIntegerEntry : map.entrySet()) {
if (integerIntegerEntry.getValue() > max) {
max = integerIntegerEntry.getValue();
res = integerIntegerEntry.getKey();
}
}
return res;
}
}
方法二:排序
如果將數(shù)組 nums 中的所有元素按照單調(diào)遞增或單調(diào)遞減的順序排序,那么下標(biāo)為 n/2 的元素(下標(biāo)從 0 開始)一定是眾數(shù)。
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}
方法三:隨機(jī)化
這個思路很獨特,感覺看臉。文章來源:http://www.zghlxwxcb.cn/news/detail-818600.html
因為超過 n/2 的數(shù)組下標(biāo)被眾數(shù)占據(jù)了,這樣我們隨機(jī)挑選一個下標(biāo)對應(yīng)的元素并驗證,有很大的概率能找到眾數(shù)。文章來源地址http://www.zghlxwxcb.cn/news/detail-818600.html
class Solution {
private int randRange(Random rand, int min, int max) {
return rand.nextInt(max - min) + min;
}
private int countOccurences(int[] nums, int num) {
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == num) {
count++;
}
}
return count;
}
public int majorityElement(int[] nums) {
Random rand = new Random();
int majorityCount = nums.length / 2;
while (true) {
int candidate = nums[randRange(rand, 0, nums.length)];
if (countOccurences(nums, candidate) > majorityCount) {
return candidate;
}
}
}
}
到了這里,關(guān)于面試經(jīng)典 150 題 - 多數(shù)元素的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!