Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4a5a764

Browse files
author
Openset
committed
Add: Largest Number At Least Twice of Others
1 parent 345e6dd commit 4a5a764

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,16 @@
11
package largest_number_at_least_twice_of_others
2+
3+
func dominantIndex(nums []int) int {
4+
ans, sec := 0, 0
5+
for i, v := range nums {
6+
if v > nums[ans] {
7+
ans, sec = i, nums[ans]
8+
} else if v > sec && i != ans {
9+
sec = v
10+
}
11+
}
12+
if nums[ans] >= 2*sec {
13+
return ans
14+
}
15+
return -1
16+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,39 @@
11
package largest_number_at_least_twice_of_others
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
expected int
8+
}
9+
10+
func TestDominantIndex(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: []int{3, 6, 1, 0},
14+
expected: 1,
15+
},
16+
{
17+
input: []int{1, 2, 3, 4},
18+
expected: -1,
19+
},
20+
{
21+
input: []int{1},
22+
expected: 0,
23+
},
24+
{
25+
input: []int{0, 0, 3, 2},
26+
expected: -1,
27+
},
28+
{
29+
input: []int{3, 0, 0, 2},
30+
expected: -1,
31+
},
32+
}
33+
for _, tc := range tests {
34+
output := dominantIndex(tc.input)
35+
if output != tc.expected {
36+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
37+
}
38+
}
39+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /