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

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

 1 public class Solution {
 2     public int MoreThanHalfNum_Solution(int [] array) {
 3         int len = array.length;
 4         
 5         for(int i = 0; i <= len/2;i++){
 6             int count = 0;
 7             for(int j = i;j<len;j++){
 8                 if(array[i] == array[j]){
 9                     count++;
10                 }
11             }
12             if (count > len/2)
13                 return array[i];
14         }
15         return 0;
16         
17     }
18 }

 

posted @ 2017-02-27 15:53  alittlecomputer  阅读(169)  评论(0编辑  收藏  举报