Two solutions in Java with the same running time


  • 4
    S

    public class MajorityElement {

    public int majorityElement(int[] nums) {
    	Arrays.sort(nums);
    	return nums[nums.length / 2];
    }
    
    public int majorityElement2(int[] nums) {
    	int majority = nums[0], t = 0;
    	for (int i : nums) {
    		if (i == majority) 
    			++t;
    		else if (t > 0)
    			--t;
    		else {
    			majority = i;
    			t = 1;
    		}
    	}
    	return majority;
    }
    

    }

    though these two solutions have the same running time in this platform. I still think they are different in the real application. Especially when the size of array is large and the initial order is in the worst situation, then the latter one is better.

    BTW, I do love Arrays.sort, its implementation is really amazing!


Log in to reply
 

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