本文首發(fā)于我的個人博客:尾尾部落
題目描述
數(shù)組中有一個數(shù)字出現(xiàn)的次數(shù)超過數(shù)組長度的一半,請找出這個數(shù)字。例如輸入一個長度為9的數(shù)組{1,2,3,2,2,2,5,4,2}。由于數(shù)字2在數(shù)組中出現(xiàn)了5次,超過數(shù)組長度的一半,因此輸出2。如果不存在則輸出0。
解題思路
三種解法:
- 法1:借助hashmap存儲數(shù)組中每個數(shù)出現(xiàn)的次數(shù),最后看是否有數(shù)字出現(xiàn)次數(shù)超過數(shù)組長度的一半;
- 法2:排序。數(shù)組排序后,如果某個數(shù)字出現(xiàn)次數(shù)超過數(shù)組的長度的一半,則一定會數(shù)組中間的位置。所以我們?nèi)〕雠判蚝笾虚g位置的數(shù),統(tǒng)計一下它的出現(xiàn)次數(shù)是否大于數(shù)組長度的一半;
- 法3:某個數(shù)字出現(xiàn)的次數(shù)大于數(shù)組長度的一半,意思就是它出現(xiàn)的次數(shù)比其他所有數(shù)字出現(xiàn)的次數(shù)和還要多。因此我們可以在遍歷數(shù)組的時候記錄兩個值:1. 數(shù)組中的數(shù)字;2. 次數(shù)。遍歷下一個數(shù)字時,若它與之前保存的數(shù)字相同,則次數(shù)加1,否則次數(shù)減1;若次數(shù)為0,則保存下一個數(shù)字,并將次數(shù)置為1。遍歷結(jié)束后,所保存的數(shù)字即為所求。最后再判斷它是否符合條件。
參考代碼
法1:
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int length = array.length;
for(int i=0; i<length; i++){
if(!map.containsKey(array[i]))
map.put(array[i], 1);
else
map.put(array[i], map.get(array[i])+1);
}
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
if(entry.getValue()*2>length)
return entry.getKey();
}
return 0;
}
}
法2:
import java.util.Arrays;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
Arrays.sort(array);
int half = array.length/2;
int count = 0;
for(int i=0; i<array.length; i++){
if(array[i] == array[half])
count ++;
}
if(count > half)
return array[half];
else
return 0;
}
}
法3:
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int res = array[0], count = 1;
for(int i=1; i<array.length; i++){
if(array[i] == res)
count++;
else{
count--;
}
if(count == 0){
res = array[i];
count = 1;
}
}
count = 0;
for(int i=0; i<array.length; i++){
if(array[i] == res)
count++;
}
return count > array.length/2 ? res : 0;
}
}