1. 程式人生 > >LintCode之主元素

LintCode之主元素

lintcode code 題目 取出 key += 存儲 ber pub

題目描述:

技術分享

分析:由題目可知這個數組不為空且該主元素一定存在,我選用HashMap來存儲,HashMap的存儲結構是”鍵—值對“,”鍵“用來存儲數組元素,”值“用來存儲這個元素出現的次數,然後循環遍歷這個HashMap,當發現有一個”鍵“對應的”值“大於數組元素個數的二分之一時,將這個”鍵“返回。

代碼:

 1 public class Solution {
 2     /*
 3      * @param nums: a list of integers
 4      * @return: find a  majority number
 5      */
 6     public
int majorityNumber(List<Integer> nums) { 7 // write your code here 8 HashMap<Integer,Integer> h = new HashMap<Integer,Integer>(); 9 10 int major = 0; 11 12 for(int i=0; i<nums.size(); i++) { 13 //如果該元素已存在HashMap之中 14 if
(h.containsKey(nums.get(i))) { 15 //將元素個數取出,並加1,再存回去 16 int num = h.get(nums.get(i)); 17 num += 1; 18 h.put(nums.get(i), num); 19 }else { 20 h.put(nums.get(i), 1); 21 } 22 } 23 24 int
mid = nums.size()/2; 25 26 for(int i=0; i<nums.size(); i++) { 27 if(h.get(nums.get(i)) > mid) { 28 major = nums.get(i); 29 break; 30 } 31 } 32 return major; 33 } 34 }

LintCode之主元素