1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// @Title: 最短无序连续子数组 (Shortest Unsorted Continuous Subarray)
// @Author: 15816537946@163.com
// @Date: 2019-10-11 10:15:19
// @Runtime: 28 ms
// @Memory: 6 MB
/*
 * @lc app=leetcode.cn id=581 lang=golang
 *
 * [581] 最短无序连续子数组
 *
 * https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/description/
 *
 * algorithms
 * Easy (32.92%)
 * Likes:    147
 * Dislikes: 0
 * Total Accepted:    8.8K
 * Total Submissions: 27K
 * Testcase Example:  '[2,6,4,8,10,9,15]'
 *
 * 给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。
 *
 * 你找到的子数组应是最短的,请输出它的长度。
 *
 * 示例 1:
 *
 *
 * 输入: [2, 6, 4, 8, 10, 9, 15]
 * 输出: 5
 * 解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。
 *
 *
 * 说明 :
 *
 *
 * 输入的数组长度范围在 [1, 10,000]。
 * 输入的数组可能包含重复元素 ,所以升序的意思是<=。
 *
 *
 */

func findUnsortedSubarray(nums []int) int {
	n := len(nums)
	left, right := 0, -1
	max, min := nums[0], nums[n-1]

	// 双指针
	for i := 1; i < n; i++ {

		if max <= nums[i] {
			max = nums[i]
		} else {
			right = i
		}

		j := n - 1 - i
		if min >= nums[j] {
			min = nums[j]
		} else {
			left = j
		}
	}

	return right - left + 1
}