欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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;
}