Simple Java solution


  • 0
    A
    class Solution {
        public int dominantIndex(int[] nums) {
            int index = -1,largest = -1, secondLargest = -1;
            
            for(int i=0;i<nums.length;i++){
                if(nums[i] > largest){
                    secondLargest = largest;
                    largest = nums[i];
                    index = i;
                }else if(nums[i] > secondLargest){
                    secondLargest = nums[i];
                }
            }
            
            return (largest < (2 * secondLargest)) ? -1 : index;
        }
    }
    

  • 0
    G

    @ashish53v In place of:

    secondLargest = (largest > secondLargest) ? largest : secondLargest;

    we can simply assign:

    secondLargest = largest;


  • 0
    A

    @GAGARWAL Yes, you are correct. I have updated my code. Thanks for pointing out.


Log in to reply
 

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