In a given integer array
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.
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
Approach
Java
public class LargestNumAtLeastTwice {public static void main(String[] args) {int[] nums = { 3, 6, 1, 0 };System.out.println(dominantIndex(nums));}static int dominantIndex(int[] nums) {int max1 = 0;int n = nums.length, j = 0;for (int i = 0; i < n; i++) {if (nums[i] > max1) {max1 = nums[i];j = i;}}for (int i = 0; i < n; i++) {if (i != j && nums[j] < 2 * nums[i])return -1;}return j;}}
C++
#include <bits/stdc++.h>using namespace std;int dominantIndex(vector<int> &nums){int max1 = 0;int n = nums.size(), j;for (int i = 0; i < n; i++){if (nums[i] > max1){max1 = nums[i];j = i;}}for (int i = 0; i < n; i++){if (i != j && nums[j] < 2 * nums[i])return -1;}return j;}int main(){vector<int> nums = {3, 6, 1, 0};cout << dominantIndex(nums);return 0;}
No comments:
Post a Comment