8000 :sparkles: Added solution to 581 · reverse/awesome-golang-leetcode@43322d4 · GitHub
[go: up one dir, main page]

Skip to content

Commit 43322d4

Browse files
author
Sathish Babu
committed
✨ Added solution to 581
1 parent 61bde0b commit 43322d4

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

src/0581.Shortest-Unsorted-Continuous-Subarray/Solution.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,52 @@ func Solution(nums []int) int {
1818
}
1919
return end - start + 1
2020
}
21+
22+
func Solution2(nums []int) int {
23+
n := len(nums)
24+
if n < 2 {
25+
return 0
26+
}
27+
l, r := 0, n-1
28+
for l < n-1 {
29+
if nums[l] > nums[l+1] {
30+
break
31+
}
32+
l++
33+
}
34+
for r > 0 {
35+
if nums[r] < nums[r-1] {
36+
break
37+
}
38+
r--
39+
}
40+
if l >= r {
41+
return 0
42+
}
43+
mi, ma := math.MaxInt32, math.MinInt32
44+
for i := l; i <= r; i++ {
45+
mi = min(mi, nums[i])
46+
ma = max(ma, nums[i])
47+
}
48+
for l >= 0 && mi < nums[l] {
49+
l--
50+
}
51+
for r < n && ma > nums[r] {
52+
r++
53+
}
54+
return r - l - 1
55+
}
56+
57+
func min(a, b int) int {
58+
if a < b {
59+
return a
60+
}
61+
return b
62+
}
63+
64+
func max(a, b int) int {
65+
if a > b {
66+
return a
67+
}
68+
return b
69+
}

src/0581.Shortest-Unsorted-Continuous-Subarray/Solution_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,30 @@ func TestSolution(t *testing.T) {
2929
}
3030
}
3131

32+
func TestSolution2(t *testing.T) {
33+
// 测试用例
34+
cases := []struct {
35+
name string
36+
inputs []int
37+
expect int
38+
}{
39+
{"TestCase", []int{2, 6, 4, 8, 10, 9, 15}, 5},
40+
{"TestCase", []int{1, 2, 3, 3, 3}, 0},
41+
{"TestCase", []int{1}, 0},
42+
}
43+
44+
// 开始测试
45+
for i, c := range cases {
46+
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
47+
got := Solution2(c.inputs)
48+
if !reflect.DeepEqual(got, c.expect) {
49+
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
50+
c.expect, got, c.inputs)
51+
}
52+
})
53+
}
54+
}
55+
3256
// 压力测试
3357
func BenchmarkSolution(b *testing.B) {
3458

0 commit comments

Comments
 (0)
0