[Leetcode学习-c++&java]Shortest Unsorted Continuous Subarray(找一个最短的排序距离)

问题:

难度:medium

说明:

给出一个数组,然后找到里面不是 从小到大 升序的子序列,然后计算出最短的一个,包含了所有不是升序子序列的需要排序的 子串(连续子序列)。

题目连接:https://leetcode.com/problems/shortest-unsorted-continuous-subarray/

输入范围:

  1. 1 <= nums.length <= 104
  2. -105 <= nums[i] <= 105

输入案例:

Example 1:  比如说 6, 4, 8, 10, 9 这一大串有两个不连续的非升序子序列 [6, 4] [9, 10]
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

我的代码:

因为排序可能情况有:

1,3,5,4,2 很小的 2 放到非常后面,需要往前找比它小的元素的位置
1,9,5,4,2 很大的 9 放到很前面,需要往后找比它大的元素的位置。
1,3,2,2,2 很多重复的元素放到一起,可能是小很多的,可能是大很多的 如:1,9,9,9,2,2,2

所以需要找到第一个非升序位置 begin 和最后一个非升序位置 end,然后将所有非升序位置的最大值 max 和 最小值 min 计算出来,从 begin开始找到 min 应有的位置,然后从 end 找到 max 应有的位置,两个位置相减就是需要排序的长度。

Java:

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        boolean flag = true;
        int left = 0, minL = Integer.MAX_VALUE, preR = 0, maxR = Integer.MIN_VALUE, cr = 0, right = 1, len = nums.length;
        while(right != len) {
            if(nums[right] < nums[preR]) {
                if(flag) left = right - 1;
                while(right + 1 < len && nums[right] == nums[right + 1]) right ++;
                if(flag) {
                    maxR = nums[preR];
                    while(left >= 0 && nums[right] < nums[left]) left --;
                    left ++; flag = false;
                }
                cr = right;
                maxR = Math.max(nums[preR], maxR);
                minL = Math.min(nums[right], minL);
            }
            preR = right;
            right ++;
        }
        while(cr < len && maxR > nums[cr]) cr ++;
        while(left >= 0 && minL < nums[left]) left --;
        return cr - left == 0 ? 0 : cr - left - 1;
    }
}

C++:

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        bool flag = true;
        int left = 0, minL = INT_MAX, preR = 0, maxR = INT_MIN, cr = 0, right = 1, len = nums.size();
        while(right != len) {
            if(nums[right] < nums[preR]) {
                if(flag) left = right - 1;
                while(right + 1 < len && nums[right] == nums[right + 1]) right ++;
                if(flag) {
                    maxR = nums[preR];
                    while(left >= 0 && nums[right] < nums[left]) left --;
                    left ++; flag = false;
                }
                cr = right;
                maxR = max(nums[preR], maxR);
                minL = min(nums[right], minL);
            }
            preR = right;
            right ++;
        }
        while(cr < len && maxR > nums[cr]) cr ++;
        while(left >= 0 && minL < nums[left]) left --;
        return cr - left == 0 ? 0 : cr - left - 1;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/114115920