easy to understand Java code O(N)


  • 0
    Y
    public class Solution {
        public int findUnsortedSubarray(int[] nums) {
            int start = -1, end = -1, l = nums.length;
            int max = nums[0], min = nums[l-1];
            for (int i = 1; i < l; i++) {
                if (max > nums[i]) {
                    end = i; 
                }
                max = Math.max(max, nums[i]);    
            }
            for (int i = l-2; i >= 0; i--) {
                if (min < nums[i]) {
                    start = i;
                }   
                min = Math.min(min, nums[i]);
            }
            
            if (start == -1 && end == -1) {
                return 0;    
            } 
            return end-start+1;
        }
    }
    

Log in to reply
 

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