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:
- Then length of the input array is in range [1, 10,000].
- The input array may contain duplicates, so ascending order here means <=.
题意:
求一个数组的子数组,将子数组排序后则整个数组有序,从小到大。求这个子数组的长度。
思路:
将数组拷贝一份,再排序。对比原数组和排序后的,首尾第一个不相同的位置即是子数组的首尾。
代码:
class Solution {
public int findUnsortedSubarray(int[] nums) {
int n=nums.length;
//int[]t=nums 赋值引用,改变nums它也会改变
int[]t=new int[n];
System.arraycopy(nums, 0, t, 0, n);
Arrays.sort(nums);
int b=0,e=0;
for(int i=0;i<n;i++)
{
if(t[i]!=nums[i])
{
b=i;
break;
}
}
for(int i=n-1;i>=0;i--)
{
if(t[i]!=nums[i])
{
e=i;
break;
}
}
if(b==0&&e==0)
return 0;
return e-b+1;
}
}
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
int n=nums.size();
// vector<int>t(nums);
vector<int>t;
t.assign(nums.begin(),nums.end());
sort(nums.begin(),nums.end());
int b=0,e=0;
for(int i=0;i<n;i++)
{
if(t[i]!=nums[i])
{
b=i;
break;
}
}
for(int i=n-1;i>=0;i--)
{
if(t[i]!=nums[i])
{
e=i;
break;
}
}
if(b==0&&e==0)
return 0;
return e-b+1;
}
};