Go/Leet Code
Array and String - Largest Number At Least Twice of Others in Go
Gopythor
2022. 3. 24. 18:32
728x90
반응형
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:
- 1 <= nums.length <= 50
- 0 <= nums[i] <= 100
- The largest element in nums is unique.
My code
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
}
- Just made simple code
- Find greatest number and if so put second.
- If not put it to second.
sample 1 ms submission
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
}
- This code uses edge case for length 1 array.
- First for loop checks value is greater than nums[max].
- If so, i will be allocated.
- Second for loop will do again.
- I think that is not good because one time for loop is enough.
- when max is same with index, it continues.
sample 5 ms submission
// 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
}
- this code allocate 0 to highestindex.
- So that for loop starts from 1.
728x90
반응형