美文网首页
747. Largest Number Greater Than

747. Largest Number Greater Than

作者: DrunkPian0 | 来源:发表于2017-12-24 11:15 被阅读20次

    https://leetcode.com/contest/weekly-contest-64/problems/largest-number-greater-than-twice-of-others/

    In a given integer array nums, there is always exactly one largest element.
    Find whether the largest element in the array is at least twice as much as every other number in the array.
    If it is, return the index of the largest element, otherwise return -1.
    Example 1:
    Input: nums = [3, 6, 1, 0]
    Output: 1
    Explanation: 6 is the largest integer, and for every other number in the array x,
    6 is more than twice as big as x. The index of value 6 is 1, so we return 1.
    Example 2:
    Input: nums = [1, 2, 3, 4]
    Output: -1
    Explanation: 4 isn't at least as big as twice the value of 3, so we return -1.
    Note:
    nums will have a length in the range [1, 50].
    Every nums[i] will be an integer in the range [0, 99].

    本周Contest签到题。
    一次AC了,维护最大和次大的数的val和index,用了一个Pair类,时间O(n)。
    注意要初始化数组里的成员。

        //  [3, 6, 1, 0]
        //  [1, 2, 3, 4]
        public int dominantIndex(int[] nums) {
            if (nums == null || nums.length <= 1) {
                return -1;
            }
            Pair[] temp = new Pair[2];
            temp[0] = new Pair();
            temp[1] = new Pair();
            temp[1].val = nums[0];
            temp[1].index = 0;
            for (int i = 1; i < nums.length; i++) {
                if (nums[i] >= temp[1].val) {
                    temp[0].val = temp[1].val;
                    temp[0].index = temp[1].index;
                    temp[1].val = nums[i];
                    temp[1].index = i;
                } else if (nums[i] > temp[0].val) {
                    temp[0].val = nums[i];
                    temp[0].index = i;
                }
            }
            if (temp[1].val >= 2 * temp[0].val) {
                return temp[1].index;
            } else {
                return -1;
            }
        }
    
        class Pair {
            int val;
            int index;
        }
    

    相关文章

      网友评论

          本文标题:747. Largest Number Greater Than

          本文链接:https://www.haomeiwen.com/subject/wdocgxtx.html