Skip to content

Commit e014be6

Browse files
committed
add 611 solution
1 parent a16e51a commit e014be6

File tree

3 files changed

+124
-0
lines changed

3 files changed

+124
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# [611. Valid Triangle Number][title]
2+
3+
## Description
4+
5+
Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
6+
**Example 1:**
7+
8+
```
9+
Input: a = "11", b = "1"
10+
Output: "100"
11+
```
12+
13+
**Example 2:**
14+
15+
```
16+
Input: a = "1010", b = "1011"
17+
Output: "10101"
18+
```
19+
20+
**Tags:** Math, String
21+
22+
## 题意
23+
> 求2数之和
24+
25+
## 题解
26+
27+
### 思路1
28+
> 。。。。
29+
30+
```go
31+
32+
```
33+
34+
### 思路2
35+
> 思路2
36+
```go
37+
38+
```
39+
40+
## 结语
41+
42+
如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-leetcode][me]
43+
44+
[title]: https://leetcode.com/problems/valid-triangle-number/
45+
[me]: https://github.com/kylesliu/awesome-golang-leetcode
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package Solution
2+
3+
func triangleNumber(nums []int) int {
4+
n, ans := len(nums), 0
5+
nums = Sort(nums)
6+
for c := 0; c < n-1; c++ {
7+
a, b := n-1, c+1
8+
for b < a {
9+
if nums[a]+nums[b] > nums[c] {
10+
ans += (a - b)
11+
b++
12+
} else {
13+
a--
14+
}
15+
}
16+
17+
}
18+
return ans
19+
}
20+
21+
func Sort(nums []int) []int {
22+
if len(nums) == 0 {
23+
return []int{}
24+
}
25+
max := nums[0]
26+
var left_res, right_res, res []int
27+
for i := 1; i < len(nums); i++ {
28+
if nums[i] > max {
29+
left_res = append(left_res, nums[i])
30+
} else {
31+
right_res = append(right_res, nums[i])
32+
}
33+
}
34+
left_res = Sort(left_res)
35+
right_res = Sort(right_res)
36+
res = append(res, left_res...)
37+
res = append(res, max)
38+
res = append(res, right_res...)
39+
return res
40+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package Solution
2+
3+
import (
4+
"reflect"
5+
"strconv"
6+
"testing"
7+
)
8+
9+
func TestSolution(t *testing.T) {
10+
// 测试用例
11+
cases := []struct {
12+
name string
13+
inputs []int
14+
expect int
15+
}{
16+
{"TestCase", []int{2, 2, 3, 4}, 3},
17+
}
18+
19+
// 开始测试
20+
for i, c := range cases {
21+
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
22+
got := triangleNumber(c.inputs)
23+
if !reflect.DeepEqual(got, c.expect) {
24+
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
25+
c.expect, got, c.inputs)
26+
}
27+
})
28+
}
29+
}
30+
31+
// 压力测试
32+
func BenchmarkSolution(b *testing.B) {
33+
34+
}
35+
36+
// 使用案列
37+
func ExampleSolution() {
38+
39+
}

0 commit comments

Comments
 (0)