Java Solution


  • 0
    Y

    Iterate the array and find largest and second largest number. Check if largest is twice as the second largest.

    class Solution {
        public int dominantIndex(int[] nums) {
            
            int maxnum=0, second=0, maxidx=0;
            for (int i=0; i<nums.length; i++) {
                if (nums[i] > maxnum) {
                    second = maxnum;
                    maxnum = nums[i];
                    maxidx = i;
                }
                else {
                    if (nums[i] > second) {
                        second = nums[i];
                    }
                }
            }
            if (maxnum >= 2*second) {
                return maxidx;
            }
            return -1;
            
        }
    }
    

Log in to reply
 

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