.
题目
Given an integer array nums, 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.
Return the shortest such subarray and output its length.
Example 1:
Input: nums = [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.
Example 2:
Input: nums = [1,2,3,4]
Output: 0
Example 3:
Input: nums = [1]
Output: 0
Constraints:
1 <= nums.length <= 10^4
-10^5 <= nums[i] <= 10^5
Follow up: Can you solve it in O(n) time complexity?
.
代码
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
if (nums.size() < 2)
return 0;
vector<int> numsCopy = nums;
sort(numsCopy.begin(), numsCopy.end());
int length = 0, ascend = 0;
for (int i = 0; i < nums.size(); i++)
{
if (numsCopy[i] != nums[i])
{
length += ascend + 1;
ascend = 0;
}
else if(length)
ascend++;
}
return length;
}
};
.
题后记
转眼,二月就过去了。每年春节过完的时候,只要还是二月,就觉得还是新年,便有了理由可以松懈、可以偷懒。二月过去,便意味着新的一年正式开始了,也不可再懒惰。
今年的二月有些特别,几乎每天都在学习和逃避学习之间摇摆。恍然一个月过后,也突然发现,自己好像也有了些许的不同。付出的努力虽然还没有非常显现,但心理上却获得了一些安慰。
今年二月有冬奥会的开幕,认识了谷爱凌,对冰雪运动开始好奇。今年二月也有源源不断的国际形势变化,不经意间多了很多不安。同时,也带了很多思考。
愿世界和平。我们能做的很少,那就继续好好努力吧。
你好,三月。