1. 程式人生 > >劍指offer-數組中超過一半的數字

劍指offer-數組中超過一半的數字

== color AR get put ava imp 由於 AI

題目描述:數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。例如輸入一個長度為9的數組{1,2,3,2,2,2,5,4,2}。由於數字2在數組中出現了5次,超過數組長度的一半,因此輸出2。如果不存在則輸出0。

思路:利用map

ac代碼:

 1 import java.util.HashMap;
 2 import java.util.List;
 3 import java.util.Map;
 4 public class Solution {
 5     public int MoreThanHalfNum_Solution(int [] array) {
 6         Map<Integer,Integer>map=new
HashMap<Integer, Integer>(); 7 int n=array.length; 8 if(n==1) 9 return array[0]; 10 int x; 11 boolean flag=false; 12 for(int i=0;i<n;i++){ 13 x=array[i]; 14 if(map.containsKey(x)){ 15 map.put(x, map.get(x)+1);
16 if(map.get(x)>n/2){ 17 return x; 18 } 19 }else{ 20 map.put(x,1); 21 } 22 } 23 return 0; 24 } 25 }

劍指offer-數組中超過一半的數字