go: add «2780. Minimum Index of a Valid Split»
URL: https://leetcode.com/problems/minimum-index-of-a-valid-split/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
3a02219766
commit
d98d57439f
1 changed files with 47 additions and 0 deletions
47
go/minimum-index-of-a-valid-split.go
Normal file
47
go/minimum-index-of-a-valid-split.go
Normal file
|
@ -0,0 +1,47 @@
|
|||
package main
|
||||
|
||||
func minimumIndex(nums []int) int {
|
||||
majorityElement := func() int {
|
||||
dom, count := nums[0], 0
|
||||
|
||||
for _, x := range nums {
|
||||
if x == dom {
|
||||
count++
|
||||
} else {
|
||||
count--
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
dom = x
|
||||
count = 1
|
||||
}
|
||||
}
|
||||
|
||||
return dom
|
||||
}
|
||||
dom := majorityElement()
|
||||
|
||||
// get frequency
|
||||
domCount := 0
|
||||
for _, x := range nums {
|
||||
if x == dom {
|
||||
domCount++
|
||||
}
|
||||
}
|
||||
|
||||
// Check for split
|
||||
count := 0
|
||||
for i, x := range nums {
|
||||
if x == dom {
|
||||
count++
|
||||
}
|
||||
|
||||
remaining := domCount - count
|
||||
if 2*count > i+1 && 2*remaining > len(nums)-i-1 {
|
||||
return i
|
||||
}
|
||||
}
|
||||
|
||||
// couldn't find a valid split
|
||||
return -1
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue