Skip to content

Commit d81fd2b

Browse files
author
baxiang
committed
Merge branch 'master' of github.com:baxiang/leetcode-go
2 parents 6059824 + 39dd467 commit d81fd2b

File tree

3 files changed

+96
-0
lines changed
  • 443string-compression
  • 84largest-rectangle-in-histogram
  • 974subarray-sums-divisible-by-k

3 files changed

+96
-0
lines changed

443string-compression/main.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"strconv"
6+
)
7+
8+
func compress(chars []byte) int {
9+
var anchor = 0
10+
var write = 0
11+
for read := 0; read < len(chars); read++ {
12+
if read+1 == len(chars) || chars[read+1] != chars[read] {
13+
chars[write] = chars[anchor]
14+
write++
15+
if read > anchor {
16+
char := strconv.Itoa(read - anchor + 1)
17+
for i := 0; i < len(char); i++ {
18+
chars[write] = char[i]
19+
write++
20+
}
21+
}
22+
anchor = read + 1
23+
}
24+
}
25+
return write
26+
}
27+
28+
func main() {
29+
fmt.Println(compress([]byte{'a', 'a', 'a', 'b', 'b'}))
30+
fmt.Println(compress([]byte{'a','a','b','b','c','c','c'}))
31+
fmt.Println(compress([]byte{'a'}))
32+
fmt.Println(compress([]byte{'a','b','b','b','b','b','b','b','b','b','b','b','b'}))
33+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func largestRectangleArea(heights []int) int {
6+
var res int
7+
for i := 0; i < len(heights); i++ {
8+
var min = heights[i]
9+
for j := i; j < len(heights); j++ {
10+
if min > heights[j] {
11+
min = heights[j]
12+
}
13+
width := j - i + 1
14+
area := min * width
15+
if area > res {
16+
res = area
17+
}
18+
}
19+
}
20+
return res
21+
}
22+
23+
func main() {
24+
fmt.Println(largestRectangleArea([]int{2, 1, 5, 6, 2, 3}))
25+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func subarraysDivByK1(A []int, K int) int {
6+
var res int
7+
for i := 0; i < len(A); i++ {
8+
var sum =0
9+
for j := i ; j <len(A); j++ {
10+
sum +=A[j]
11+
if sum%K == 0 {
12+
res++
13+
}
14+
}
15+
}
16+
return res
17+
}
18+
func subarraysDivByK(A []int, K int) int {
19+
record := map[int]int{0: 1} // 如果A中有元素能整除K, 那么相关元素单独能构成符合题意的子数组,需要统计
20+
prefixSum, result := 0, 0
21+
for i := 0; i < len(A); i++ {
22+
prefixSum += A[i]
23+
mod := (prefixSum % K+K)%K
24+
//if mod < 0 { // prefixSum可能是负数,导致mod为负数, 取余的结果mod为负,跟取余结果为mod+K是等价的
25+
// mod += K
26+
//}
27+
fmt.Println(mod)
28+
result += record[mod]
29+
record[mod]++
30+
}
31+
return result
32+
}
33+
34+
35+
func main() {
36+
subarraysDivByK([]int{4, 5, 0, -2, -3, 1}, 5)
37+
fmt.Println()
38+
}

0 commit comments

Comments
 (0)