581. Shortest Unsorted Continuous Subarray

2018/04/10 leetcode 共 1909 字,约 6 分钟

Title

the problem link

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

题目大意,找到子数组的长度,将这个子数组排序后就可以让这个数组有序了,通过排序然后对比原来数组就可以得到结果

Solution

这个还有待扩展,这个时间复杂度太高了,有时间得看下那个solution

//cpp:

class Solution {
public:
	int findUnsortedSubarray(vector<int>& nums) {
		vector<int> v(nums);
		sort(v.begin(), v.end(), less<int>());
		int left = 0, right = 0;
		for (int i = 0; i < nums.size(); i++) {
			if (v[i] == nums[i])
				left++;
			else
				break;
		}
		for (int i = nums.size() - 1; i >= 0; i--) {
			if (v[i] == nums[i]&&i>left)
				right++;
			else
				break;
		}
		return nums.size() - left - right;
	}
};

public class Solution {
    public int findUnsortedSubarray(int[] nums) {
        Stack < Integer > stack = new Stack < Integer > ();
        int l = nums.length, r = 0;
        for (int i = 0; i < nums.length; i++) {
            while (!stack.isEmpty() && nums[stack.peek()] > nums[i])
                l = Math.min(l, stack.pop());
            stack.push(i);
        }
        stack.clear();
        for (int i = nums.length - 1; i >= 0; i--) {
            while (!stack.isEmpty() && nums[stack.peek()] < nums[i])
                r = Math.max(r, stack.pop());
            stack.push(i);
        }
        return r - l > 0 ? r - l + 1 : 0;
    }
}
public class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
        boolean flag = false;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] < nums[i - 1])
                flag = true;
            if (flag)
                min = Math.min(min, nums[i]);
        }
        flag = false;
        for (int i = nums.length - 2; i >= 0; i--) {
            if (nums[i] > nums[i + 1])
                flag = true;
            if (flag)
                max = Math.max(max, nums[i]);
        }
        int l, r;
        for (l = 0; l < nums.length; l++) {
            if (min < nums[l])
                break;
        }
        for (r = nums.length - 1; r >= 0; r--) {
            if (max > nums[r])
                break;
        }
        return r - l < 0 ? 0 : r - l + 1;
    }
}

Search

    Table of Contents