Shortest Unsorted Continuous Subarray
这道题为简单题
题目:
思路:
我的思路:先给数组排序,然后遍历两个数组,如果相同索引元素不相等,first=i,直到最后一次不相等时,second=i.最后返回second-first+1,最开始初始化为-1和-2是为了方便计算如果nums数组一直都是递增的情况
大神:最开始我也是跟它想法一样,但是始终没做出来,首先前后遍历列表,找到最大最小值,从而锁定beg和end
代码:
我的代码:
1 class Solution(object): 2 def findUnsortedSubarray(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 a = sorted(nums) 8 first = -1 9 second = -2 10 for i in range(len(a)): 11 if first == -1 and a[i] != nums[i]: first = i 12 elif a[i] != nums[i]: second = i 13 return second - first + 1
大神的代码(Java):
1 public int findUnsortedSubarray(int[] A) { 2 int n = A.length, beg = -1, end = -2, min = A[n-1], max = A[0]; 3 for (int i=1;i<n;i++) { 4 max = Math.max(max, A[i]); 5 min = Math.min(min, A[n-1-i]); 6 if (A[i] < max) end = i; 7 if (A[n-1-i] > min) beg = n-1-i; 8 } 9 return end - beg + 1; 10 }