C++ Concise O(n) Solution


  • 0
    Z
    class Solution {
    public:
        int findUnsortedSubarray(vector<int>& nums) {
            if (nums.empty()) return 0;
            int len = nums.size(), lo = len - 1, hi = 0;
            for (int i = 1, tmax = nums[0]; i < len; ++i) {
                if (nums[i] < nums[i - 1] || tmax > nums[i]) {
                    tmax = max(tmax, nums[i - 1]);
                    hi = i;
                }
            }
            for (int i = len - 2, tmin = nums[i - 1]; i >= 0; --i) {
                if (nums[i] > nums[i + 1] || tmin < nums[i]) {
                    tmin = min(tmin, nums[i + 1]);
                    lo = i;
                }
            }
            return lo < hi ? hi - lo + 1 : 0;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.