add new solutions
This commit is contained in:
parent
f249852923
commit
f297e11859
10 changed files with 373 additions and 0 deletions
44
solutions/15/q1536/solution.go
Normal file
44
solutions/15/q1536/solution.go
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
// Package q1536 implements a solution for https://leetcode.com/problems/minimum-swaps-to-arrange-a-binary-grid/
|
||||
package q1536
|
||||
|
||||
func minSwaps(grid [][]int) int {
|
||||
n := len(grid)
|
||||
|
||||
zeros := grid[0] // reuse memory
|
||||
for i := range grid {
|
||||
z := n - 1
|
||||
for z >= 0 && grid[i][z] == 0 {
|
||||
z--
|
||||
}
|
||||
zeros[i] = n - z - 1
|
||||
}
|
||||
|
||||
steps := 0
|
||||
for row := range n - 1 {
|
||||
needZ := n - row - 1
|
||||
if zeros[row] >= needZ {
|
||||
continue
|
||||
}
|
||||
|
||||
// Find a row with at lease needZ zeros at the end
|
||||
found := -1
|
||||
for i := row + 1; i < n; i++ {
|
||||
if zeros[i] >= needZ {
|
||||
found = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if found == -1 {
|
||||
return -1
|
||||
}
|
||||
|
||||
steps += found - row
|
||||
t := zeros[found]
|
||||
copy(zeros[row+1:found+1], zeros[row:found])
|
||||
zeros[row] = t
|
||||
}
|
||||
|
||||
return steps
|
||||
}
|
||||
|
||||
var _ = minSwaps
|
||||
Loading…
Add table
Add a link
Reference in a new issue