My Java solution using ArrayList to keep track of counted items


  • 0
    A

    Here it is:

    I'm curious about the bit manipulation solution... anyone figure it out?

    ```import java.util.ArrayList;
    
    
    
    public class Solution {
    
    	public int numOccurences(int[] arr, int val)
    	{
    		int occurences = 0;
    		for(int i = arr.length - 1; i >= 0; --i)
    		{
    			if(arr[i] == val) ++occurences;
    		}
    		return occurences;
    	}
        public int majorityElement(int[] num) {
        	
        	ArrayList<Integer> checked = new ArrayList<Integer>();
        	
        	int majority = 0;
        	int maxOccurences = 0;
        	for(int i = num.length -1 ; i >= 0; --i)
        	{
        		int currentLookup = num[i], occurences = 0;
        		if(checked.contains(currentLookup)) continue;
        		occurences = numOccurences(num, currentLookup);
        		checked.add(currentLookup);
        		if(occurences > maxOccurences)
        		{
        			majority = currentLookup;
        			maxOccurences = occurences;
        		}
        		
        	}
            return majority;
        }
    }```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.