原题链接在这里:https://leetcode.com/problems/shortest-unsorted-continuous-subarray/

题目:

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: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

Note:

  1. Then length of the input array is in range [1, 10,000].
  2. The input array may contain duplicates, so ascending order here means <=.

题解:

If the input nums is not sorted, then we want to find out the boundary index.

Then how, lets take start position as example. If the first part is sorted, then traversing right -> left, the updated minimum should be nums[i].

We want to find out the position when minimum != nums[i], and the most left one, then it should be start position of output.

Vice versa for the ending position.

Time Complexity: O(nums.length).

Space: O(1).

AC Java:

 class Solution {
public int findUnsortedSubarray(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
} int s = -1;
int e = -2;
int len = nums.length;
int max = nums[0];
int min = nums[len-1];
for(int i = 0; i<len; i++){
max = Math.max(max, nums[i]);
if(max != nums[i]){
e = i;
} min = Math.min(min, nums[len-1-i]);
if(min != nums[len-1-i]){
s = len-1-i;
}
} return e-s+1;
}
}

最新文章

  1. ngBind ngBindTemplate ngBindHtml
  2. ubuntu16041,安装opencv3.1.0
  3. 区块 Blocks
  4. FMX 讯息框 FrameDialog
  5. 吉他笔记 solo 和弦 推弦 音程
  6. MangoDB的C#Driver驱动简单例子
  7. [独孤九剑]持续集成实践(二)– MSBuild语法入门
  8. linux c信息验证程序(分享)
  9. 两个php.ini; ubuntu下配置文件
  10. cf C. Purification
  11. 步步学LINQ to SQL:将类映射到数据库表【转】
  12. mysql HA方案: MHA
  13. Ubuntu14.04下SP_Flash_Tool_exe_Linux无法烧录
  14. 【Ruby on Rails】Model中关于保存之前的原值和修改状态
  15. java学习笔记之字符流文件复制
  16. PHP定义字符串的四种方式
  17. Mycat 分片规则详解--枚举分片
  18. NuGet 手动清除缓存不起作用
  19. DRF的解析器和渲染器
  20. VB 共享软件防破解设计技术初探(二)

热门文章

  1. I.MX6Q(TQIMX6Q/TQE9)学习笔记——U-Boot移植
  2. java屏幕截取
  3. shell的符号总结
  4. JavaWeb CSS
  5. Docker 数据管理-tmpfs mounts
  6. mongodb 中的Multikey Index Bounds解释$elemMatch
  7. RabbitMQ死信队列
  8. 使用 grep 查找所有包含指定文本的文件
  9. HTML中table边框的显示总结
  10. php环境之Wampserver端口修改