/*第一种方法
先将数组进行快排,如果数组中有一个数字出现的次数超过数组长度的一半,
那么快排后数组中间的数就一定是这个数字。
遍历快排后的数组,如果最中间的数的个数大于数组长度的一半,则输出这个数,否则输出0;
*/
import java.util.Arrays;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array.length == 0 || array == null){
return 0;
}
Arrays.sort(array);
int temp = array[array.length/2];
int j = 0;
for(int i = 0;i < array.length;i++){
if(array[i] == temp){
j++;
}
}
return j > array.length/2 ? temp : 0 ;
}
}
/*第二种方法:
*/
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array.length == 0 || array == null){
return 0;
}
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0;i < array.length;i++){
Integer temp = map.get(array[i]);
if(temp == null){
map.put(array[i],1);
temp = 1;
}
else{
map.put(array[i],temp+1);
}
if(temp+1 > array.length/2){
return array[i];
}
}
return 0;
}
}
//经过修改之后的第三种方法,供大家研究:
import java.util.*;
public class Solution {
public int MoreThanHalfNum_Solution(int[] array) {
if (array.length == 0 || array == null) {
return 0;
}
int num = array[0], count = 1;
for (int i = 1; i < array.length; i++) {
if (array[i] == num)
count++;
else
count--;
if (count == 0) {
num = array[i];
count = 1;
}
}
count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == num) {
count++;
}
}
return count > array.length / 2 ? num : 0;
}
}