Largest Number At Least Twice of Others LT747

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:

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

 Idea 1. Scan the array to find the maxIndex and secondMax

Time complexity: O(N)

Space complexity: O(1)

 1 class Solution {
 2     public int dominantIndex(int[] nums) {
 3         int maxIndex = -1;
 4         int secondMax = Integer.MIN_VALUE;
 5         
 6         for(int i = 0; i < nums.length; ++i) {
 7             if(maxIndex == -1) {
 8                 maxIndex = i;
 9             }
10             else if(nums[maxIndex] < nums[i]) {
11                 secondMax = nums[maxIndex];
12                 maxIndex = i;
13             }
14             else if(secondMax < nums[i]) {
15                 secondMax = nums[i];
16             }
17         }
18         
19         if(nums[maxIndex] >= 2 * secondMax) {
20             return maxIndex;
21         }
22         
23         return -1;
24     }
25 }

Idea 1.b Two scan to find the max and compare with the other element separately

Time complexity: O(N), 2 scan

Space complexity: O(1)

 1 class Solution {
 2     public int dominantIndex(int[] nums) {
 3         int maxIndex = -1;
 4         
 5         for(int i = 0; i < nums.length; ++i) {
 6             if(maxIndex == -1 || nums[i] > nums[maxIndex]) {
 7                 maxIndex = i;
 8             }
 9         }
10         
11         for(int i = 0; i < nums.length; ++i) {
12             if(maxIndex != i && nums[maxIndex] < 2 * nums[i]) {
13                 return -1;
14             }
15         }
16         
17         return maxIndex;
18     }
19 }

猜你喜欢

转载自www.cnblogs.com/taste-it-own-it-love-it/p/10836276.html
今日推荐