leetCode-Shortest Unsorted Continuous Subarray
来源:互联网 发布:水晶古筝知乎 编辑:程序博客网 时间:2024/06/14 10:20
Description:
Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
You need to find the shortest such subarray and output its length.
Example 1:
Input: [2, 6, 4, 8, 10, 9, 15]Output: 5Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
Note:
Then length of the input array is in range [1, 10,000].The input array may contain duplicates, so ascending order here means <=.
Solution:
public class Solution { public int findUnsortedSubarray(int[] nums) { int n = nums.length; int[] temp = nums.clone(); Arrays.sort(temp); int start = 0; while (start < n && nums[start] == temp[start]) start++; int end = n - 1; while (end > start && nums[end] == temp[end]) end--; return end - start + 1; }}
Better Solution:
//low和high分别存储nums中从左边和右边遍历不满足有序的下标,找到low和high,然后找出low和high之间的最小值和最大值,从low向左遍历nums,将low定位到比low和high之间最小值还小的小标,从high向右遍历nums,将high定位到比low和high之间最大值还大的小标。将high-low-1即为无序长度class Solution { public int findUnsortedSubarray(int[] nums) { int low = 0, high = nums.length-1, max = Integer.MIN_VALUE, min = Integer.MAX_VALUE; while(low<high&&nums[low+1]>=nums[low]) low++; while(high>low&&nums[high-1]<=nums[high]) high--; if(low>=high) return 0; for(int i= low;i<=high;i++){ max =Math.max(max, nums[i]); min = Math.min(min, nums[i]); } while(low>=0&&nums[low]>min) low--; while(high<=nums.length-1&&nums[high]<max) high++; return high- low -1; }
阅读全文
0 0
- LeetCode Shortest Unsorted Continuous Subarray
- leetcode Shortest Unsorted Continuous Subarray
- leetCode-Shortest Unsorted Continuous Subarray
- [LeetCode]581. Shortest Unsorted Continuous Subarray
- leetcode 581. Shortest Unsorted Continuous Subarray
- leetcode 581: Shortest Unsorted Continuous Subarray
- [LeetCode]581. Shortest Unsorted Continuous Subarray
- [leetcode]581. Shortest Unsorted Continuous Subarray
- [leetcode]581. Shortest Unsorted Continuous Subarray
- 【LeetCode】581. Shortest Unsorted Continuous Subarray
- LeetCode 581. Shortest Unsorted Continuous Subarray
- 20170606-leetcode-581-Shortest Unsorted Continuous Subarray
- [leetcode]: 581. Shortest Unsorted Continuous Subarray
- [LeetCode] 581. Shortest Unsorted Continuous Subarray
- Leetcode 581 Shortest Unsorted Continuous Subarray
- [LeetCode] 581. Shortest Unsorted Continuous Subarray
- LeetCode 581. Shortest Unsorted Continuous Subarray
- LeetCode刷题【Array】 Shortest Unsorted Continuous Subarray
- Hadoop平台搭建
- 自然语言处理(二 RNN语言模型)
- gulp配置笔记
- Disjoint Sparse Table(不相交散列表)模板
- TCP连接的建立与终止
- leetCode-Shortest Unsorted Continuous Subarray
- windows10下JAVA中环境变量的设置
- I
- BP神经网络示例(Matlab)
- 我使用过的Linux命令之file
- 教程篇(5.4) NSE4 21. 诊断 ❀ 飞塔 (Fortinet) 网络安全专家
- mysql5.7官网直译SQL语句优化--行结构表达式的优化
- hdoj-1686Oulipo(Kmp)
- nginx之反向代理实践理解