Wednesday, December 31, 2014

Majority Element (LeetCode Array)

Question: 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.

Idea: Scan the array from left to right. Use a Hashmap<value, times appeared> to record how many times each value shows up. Once a value shows up more than floor(n/2) times, return it as the result.

Time: O(n) Space: O(n)

Code:
 public class Solution {  
   public int majorityElement(int[] num) {  
     HashMap<Integer,Integer> appeared=new HashMap<Integer,Integer>();  
     int threshold=num.length/2;  
     for(int i:num)  
     {  
       if(appeared.containsKey(i))  
         appeared.put(i,appeared.get(i)+1);  
       else  
         appeared.put(i,1);  
       if(appeared.get(i)>threshold)  
         return i;  
     }  
     return -1;  
   }  
 }  

1 comment:

  1. This should be possible in O(n) time and O(1) space. See the algorithm introduction here:
    http://www.sysexpand.com/?path=exercises/majority-element

    ReplyDelete