数组中有一个数字出现的次数超过数组长度的一半

题目:

数组中有一个数字出现的次数超过数组长度的一半。请找出这个数字。

解答:

 1 public class Solution {
 2     public static void main(String[] args) {
 3         int[] arr = {1,2,3,2,2,2,5,4,2};
 4 
 5         System.out.println(findNum(arr));
 6     }
 7 
 8     private static Integer findNum(int[] arr) {
 9         if(arr == null) {
10             return null;
11         }
12 
13         int result = arr[0];
14         int count = 1;
15 
16         for(int i = 1; i < arr.lengthl i++) {
17             if(count == 0) {
18                 result = arr[i];
19                 count = 1;
20             } else if(arr[i] == result) {
21                 count++;
22             } else {
23                 count--;
24             }
25         }
26 
27         return result;
28     }
29 }

猜你喜欢

转载自www.cnblogs.com/wylwyl/p/10373932.html
今日推荐