数组中次数超过一半的数字

 1 package algorithms;
 2 
 3 /**
 4  * 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
 5  * 例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。
 6  * 由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。
 7  * 如果不存在则输出0。
 8  * 
 9  * **/
10 public class MoreThanHalfNum {
11     //思路一:某个数出现的次数超过一半  则其出现的次数比其他所有出现的次数都多
12     //因此,我们可以在遍历数组的时候保存两个值,一个是数字,另一个是次数
13     //当我们遍历到下一个数字的时候,如果两数相同  则次数加一
14     //若不同 则次数减一
15     //若次数减为0  则保存下一个数字
16     public int MoreThanHalfNum_Solution(int [] array) {
17         if(array.length==0)
18             return 0;
19         int times = 0;
20         int now = array[0];
21         for(int i=0;i<array.length;i++) {
22             if(now == array[i])
23                 times++;
24             else
25                 times--;
26             if(i<array.length-1 && times==0)
27                 now = array[i+1];
28         }
29         int count=0;
30         for(int i=0;i<array.length;i++) {
31             if(now==array[i])
32                 count++;
33         }
34         if(count*2<=array.length)
35             return 0;
36         return now;
37         
38     }
39     
40     //思路二:如果数组中某个数字的次数超过一半,则将该数组排序后,中间位置上的数一定是该数字
41     //学会使用Arrays工具类
42     /*
43      * public class Solution {
44         public int MoreThanHalfNum_Solution(int [] array) {
45             int len=array.length;
46             if(len<1){
47                 return 0;
48             }
49             int count=0;
50             Arrays.sort(array);
51             int num=array[len/2];
52             for(int i=0;i<len;i++){
53                 if(num==array[i])
54                     count++;
55             }
56             if(count<=(len/2)){
57                 num=0;
58             }
59             return num;
60         }
61     }
62     */
63 }
原文地址:https://www.cnblogs.com/ustc-anmin/p/10619765.html