Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit fd0ccd3

Browse files
committedJul 25, 2021
Add solution and test-cases for problem 149
1 parent e7cb914 commit fd0ccd3

File tree

2 files changed

+75
-7
lines changed

2 files changed

+75
-7
lines changed
 
Lines changed: 70 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,73 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
import "fmt"
4+
5+
func Solution(points [][]int) int {
6+
if len(points) == 1 {
7+
return 1
8+
}
9+
_max := 0
10+
for idx := 1; idx < len(points); idx++ {
11+
tmpSlopes := make(map[string]int)
12+
tmpMax := 0
13+
double := 0
14+
for inner := 0; inner < idx; inner++ {
15+
x1, y1, x2, y2 := points[inner][0], points[inner][1], points[idx][0], points[idx][1]
16+
if x1 == x2 && y1 == y2 {
17+
double++
18+
continue
19+
}
20+
k := slope(x1, y1, x2, y2)
21+
if _, ok := tmpSlopes[k]; !ok {
22+
tmpSlopes[k] = 1
23+
}
24+
tmpSlopes[k]++
25+
if tmpSlopes[k] > _max {
26+
_max = tmpSlopes[k]
27+
}
28+
}
29+
30+
if tmpMax == 0 {
31+
tmpMax = 1
32+
}
33+
tmpMax += double
34+
if tmpMax > _max {
35+
_max = tmpMax
36+
}
37+
}
38+
return _max
39+
}
40+
41+
func slope(x1, y1, x2, y2 int) string {
42+
xx := x2 - x1
43+
yy := y2 - y1
44+
if xx == 0 {
45+
return fmt.Sprintf("%d", x1)
46+
}
47+
if yy == 0 {
48+
return fmt.Sprintf("%d", y1)
49+
}
50+
flag := xx*yy < 0
51+
if xx < 0 {
52+
xx = -xx
53+
}
54+
if yy < 0 {
55+
yy = -yy
56+
}
57+
k := gcd(xx, yy)
58+
yy /= k
59+
xx /= k
60+
s := fmt.Sprintf("%d/%d", yy, xx)
61+
if flag {
62+
return "-" + s
63+
}
64+
return s
65+
}
66+
67+
// 斜率问题,考虑午饭整除的情况
68+
func gcd(x, y int) int {
69+
if y == 0 {
70+
return x
71+
}
72+
return gcd(y, x%y)
573
}

‎leetcode/101-200/0149.Max-Points-on-a-Line/Solution_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
14-
expect bool
13+
inputs [][]int
14+
expect int
1515
}{
16-
{"TestCase", true, true},
17-
{"TestCase", true, true},
18-
{"TestCase", false, false},
16+
{"TestCase1", [][]int{{1, 1}, {3, 2}, {5, 3}, {4, 1}, {2, 3}, {1, 4}}, 4},
17+
{"TestCase2", [][]int{{1, 1}, {2, 2}, {3, 3}}, 3},
18+
{"TestCase3", [][]int{{0, 0}, {4, 5}, {7, 8}, {8, 9}, {5, 6}, {3, 4}, {1, 1}}, 5},
1919
}
2020

2121
// 开始测试

0 commit comments

Comments
 (0)
Please sign in to comment.