AC JAVA solution O(n) one-pass solution


  • 1
    J

    The idea is to find the largest element and second largest element from the given nums, then compare them the way the question has described.

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

Log in to reply
 

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