JAVA 5ms answer ,any suggestion?


  • 0
    J
    public class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
       double length = nums.length;
    	int x = (int) Math.floor(length / 2);
    	int temp = 0;
    	int sum = 0;
    	if (nums.length == 1) {
    		return nums[0];
    	} else {
    		a: for (int i = 0; i < nums.length; i++) {
    			if (sum > x) {
    				temp = nums[i];
    				break;
    			}else
    				sum = 1;
    			for (int j = i + 1; j < nums.length; j++) {
    				if (nums[i] == nums[j]) {
    					sum++;
    				} else {
    					if (sum > x) {
    						temp = nums[i];
    						// sum1 = sum;
    						break a;
    					}else{
    						i = j-1;
    						break;
    					}
    					
    				}
    			}
    		}
    	}
    	return temp;
    }
    

    }


  • 1
    C

    Arrays.sort(nums);
    return nums[nums.length/2];


Log in to reply
 

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