leetcode--Majority Element

来源:互联网 发布:hishop销客多源码 编辑:程序博客网 时间:2024/06/05 09:21

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

[java] view plain copy
  1. public class Solution {  
  2.     public int majorityElement(int[] nums) {  
  3.         HashMap<Integer,Integer> map =new HashMap<Integer,Integer>();  
  4.         int mid = nums.length/2;  
  5.         for(int i = 0;i<nums.length;i++){  
  6.             if(map.containsKey(nums[i])){  
  7.                 int j = map.get(nums[i])+1;  
  8.                 if(j>=mid) return nums[i];  
  9.                 else map.put(nums[i], j);  
  10.             }else{  
  11.                 map.put(nums[i], 0);  
  12.             }  
  13.         }  
  14.         return nums[0];  
  15.     }  
  16. }

原文链接http://blog.csdn.net/crazy__chen/article/details/46388301

原创粉丝点击