747 Largest Number At Least Twice of Others

lpy1990

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.

Note:

  1. nums will have a length in the range [1, 50].
  2. Every nums[i] will be an integer in the range [0, 99].

思路

维护两个变量来记录最大值和第二最大值, 一个int变量来记录最大值的位置
遍历整个数组, 更改最大值和第二大的值。
一开始想把最大值和第二大值设置成nums[0], 但是当nums[0]是最大值会出现问题。
根据note 第一大的数起始值选择0 第二大选择-1

复杂度

时间O(n) 空间O(1)

代码

class Solution {
    public int dominantIndex(int[] nums) {
        if (nums.length == 1) {
            return 0;
        }
        int r = 0;
        int l = -1;
        int index = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] > r) {
                l = r;
                r = nums[i];
                index = i;
            } else if (nums[i] > l) {
                l = nums[i];
            }
        }
        if (r >=  2*l) {
            return index;
        }
        return -1;
    }
}
阅读 946

26 声望
10 粉丝
0 条评论
26 声望
10 粉丝
文章目录
宣传栏