LeetCode | 581. Shortest Unsorted Continuous Subarray

.

题目

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

.

题后记

转眼,二月就过去了。每年春节过完的时候,只要还是二月,就觉得还是新年,便有了理由可以松懈、可以偷懒。二月过去,便意味着新的一年正式开始了,也不可再懒惰。

今年的二月有些特别,几乎每天都在学习和逃避学习之间摇摆。恍然一个月过后,也突然发现,自己好像也有了些许的不同。付出的努力虽然还没有非常显现,但心理上却获得了一些安慰。

今年二月有冬奥会的开幕,认识了谷爱凌,对冰雪运动开始好奇。今年二月也有源源不断的国际形势变化,不经意间多了很多不安。同时,也带了很多思考。

愿世界和平。我们能做的很少,那就继续好好努力吧。

你好,三月。

.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值