Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6c2a622

Browse files
author
Shuo
authored
Merge pull request #242 from openset/develop
Add: Shortest Unsorted Continuous Subarray
2 parents 6321215 + 4cd398c commit 6c2a622

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,18 @@
11
package shortest_unsorted_continuous_subarray
2+
3+
func findUnsortedSubarray(nums []int) int {
4+
m, n, l := 0, -1, len(nums)
5+
for max, min, i, j := 0, l-1, 1, l-2; i < l; i, j = i+1, j-1 {
6+
if nums[i] < nums[max] {
7+
n = i
8+
} else if nums[i] > nums[max] {
9+
max = i
10+
}
11+
if nums[j] > nums[min] {
12+
m = j
13+
} else if nums[j] < nums[min] {
14+
min = j
15+
}
16+
}
17+
return n - m + 1
18+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,31 @@
11
package shortest_unsorted_continuous_subarray
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
input []int
7+
expected int
8+
}
9+
10+
func TestFindUnsortedSubarray(t *testing.T) {
11+
tests := [...]caseType{
12+
{
13+
input: []int{2, 6, 4, 8, 10, 9, 15},
14+
expected: 5,
15+
},
16+
{
17+
input: []int{1, 2, 3, 4},
18+
expected: 0,
19+
},
20+
{
21+
input: []int{1, 2, 4, 5, 3},
22+
expected: 3,
23+
},
24+
}
25+
for _, tc := range tests {
26+
output := findUnsortedSubarray(tc.input)
27+
if output != tc.expected {
28+
t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected)
29+
}
30+
}
31+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /