581. Shortest Unsorted Continuous Subarray(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83823218

题目:

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 <=.

解释:
先把原数组排序以后,双指针诸葛比较即可。
python代码:

class Solution(object):
    def findUnsortedSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        sorted_nums=sorted(nums)
        if sorted_nums==nums:
            return 0  
        left=0
        n=len(nums)
        right=n-1
        while left<n and nums[left]==sorted_nums[left]:
            left+=1
        while right>=0 and nums[right]==sorted_nums[right]:
            right-=1
        return right-left+1

c++代码:

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        vector<int>sorted_nums(nums);
        sort(sorted_nums.begin(),sorted_nums.end());
        if (sorted_nums==nums)
            return 0;
        int n=nums.size();
        int left=0,right=n-1;
        while (left<n && sorted_nums[left]==nums[left])
            left++;
        while(right>=0 && sorted_nums[right]==nums[right])
            right--;
        return right-left+1;
    }
};

总结:

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83823218