Shortest Unsorted Continuous Subarray问题及解法
2017-05-15 13:53
148 查看
问题描述:
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.
示例:
问题分析:
根据题意,我们可以先把数组升序排序,比较哪些元素变了,左右两边发生变化的元素的位置就是要求的子数组的长度范围。
过程详见代码:
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.
示例:
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.
问题分析:
根据题意,我们可以先把数组升序排序,比较哪些元素变了,左右两边发生变化的元素的位置就是要求的子数组的长度范围。
过程详见代码:
class Solution { public: int findUnsortedSubarray(vector<int>& nums) { vector<int> nums2 = nums; sort(nums.begin(),nums.end()); int begin = -1; int end = -2; for(int i = 0;i < nums.size(); i++) { if(nums[i] != nums2[i]) { if(begin == -1) begin = i; end = i; } } return end - begin + 1; } };
相关文章推荐
- leetcode[Shortest Unsorted Continuous Subarray]//待整理多种解法
- Leetcode之Shortest Unsorted Continuous Subarray 问题
- 同一问题的两种不同解法 : MFC8.0 与 C++ 标准库
- 称球问题的一般解法
- Hanoi(汉诺)问题的非递归解法
- 中国剩余定理:一类初数题的通用解法(除数,余数问题)(转载)
- 微软过桥问题的图论解法
- 高效的八皇后问题非递归解法
- JAVA中文问题及最优解法
- "100 个台阶"问题的 4 种解法
- 背包问题 顺推解法
- 那道据说“爱因斯坦都无法解答的问题”详细解法
- 皇后问题的一个解法
- 寻找必败态——一类博弈问题的快速解法
- 过河问题的图论解法
- 约瑟夫环问题单循环链表解法
- 大力的先入先出的库存物品,按批次出货的问题的一个解法。
- 对求解“皇后排列问题”的一个新解法!
- 称球问题的测试解法
- 洗牌问题(多种解法以高效解法)