581. Shortest Unsorted Continuous Subarray
程序员文章站
2024-02-24 15:05:40
...
用了一个辅助数组,然后排序。从数组起始位置开始,两个数组相互比较,当对应位置数字不同的时候停止,同理再从末尾开始,对应位置上比较,也是遇到不同的数字时停止,中间一段就是最短无序连续子数组
#include <iostream>
#include <algorithm>
#include "vector"
#include "string"
#include "set"
#include "queue"
#include "stack"
using namespace std;
int findUnsortedSubarray(vector<int>& nums)
{
vector<int>v=nums;
sort(v.begin(), v.end());
int i = 0;
int j = nums.size()-1;
while (i<nums.size() && v[i] == nums[i])
{
++i;
}
while (j>i && v[j] == nums[j])
{
--j;
}
return j - i + 1;
}
int main()
{
vector<int>v;
v.push_back(2);
v.push_back(6);
v.push_back(4);
v.push_back(8);
v.push_back(10);
cout << findUnsortedSubarray(v) << endl;
system("pause");
return 0;
}
上一篇: python day1
推荐阅读
-
[easy][Array]581. Shortest Unsorted Continuous Subarray
-
581. Shortest Unsorted Continuous Subarray
-
581. Shortest Unsorted Continuous Subarray
-
581. Shortest Unsorted Continuous Subarray
-
581. Shortest Unsorted Continuous Subarray
-
# 189. Rotate Array # 581. Shortest Unsorted Continuous Subarray
-
LeetCode 581. Shortest Unsorted Contimuous Subarray
-
581. Shortest Unsorted Continuous Subarray
-
leetcode(581):Shortest Unsorted Continuous Subarray
-
[LeetCode]581. Shortest Unsorted Continuous Subarray