You are given an integer array nums where the largest integer is unique.
Determine 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, or return -1 otherwise.
Example 1:
Input: nums = [3,6,1,0]
Output: 1
Explanation: 6 is the largest integer.
For every other number in the array x, 6 is at least 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 is less than twice the value of 3, so we return -1.
Example 3:
Input: nums = [1]
Output: 0
Explanation: 1 is trivially at least twice the value as any other number because there are no other numbers.
Constraints:
func dominantIndex(nums []int) int {
first := 0
index := 0
second := 0
for i, v := range nums {
if v > first {
first, second, index = v, first, i
} else if second < v {
second = v
}
}
if first < second*2 {
return -1
}
return index
}
func dominantIndex(nums []int) int {
if len(nums) == 1 {
return 0
}
max := -1
for i, val := range nums {
if max == -1 {
max = i
}
if nums[max] < val {
max = i
}
}
secondMax := -1
for i, val := range nums {
if i == max {
continue
}
if secondMax == -1 {
secondMax = i
}
if nums[secondMax] < val {
secondMax = i
}
}
if nums[secondMax]*2 <= nums[max] {
return max
}
return -1
}
// t: O(n), s: O(1)
func dominantIndex(nums []int) int {
if len(nums) == 1 {
return 0
}
highestIndex := 0
secondHighestIndex := -1
for i := 1; i < len(nums); i++ {
if nums[i] > nums[highestIndex] {
secondHighestIndex = highestIndex
highestIndex = i
} else if nums [i] > nums[secondHighestIndex] {
secondHighestIndex = i
}
}
if nums[highestIndex] >= nums[secondHighestIndex]*2 {
return highestIndex
}
return -1
}
Array and string - Introduction to 2D Array from Java to Go (1) | 2022.03.27 |
---|---|
Array and String - Plus One in Go (0) | 2022.03.26 |
Array and String - Find Pivot Index in Go (0) | 2022.03.24 |
Array and string - Introduction to Dynamic Array from Java to Go (0) | 2022.03.23 |
Array and String - Introduction to Array from java to Go (0) | 2022.03.22 |
댓글 영역