Java solution without sort


  • 1
    P

    public class Solution {
    public int findUnsortedSubarray(int[] nums) {
    if (nums.length ==0) {
    return 0;
    }

        int left = 0, right = nums.length - 1;
        
        while (left < right  && nums[left] <= nums[left +1]) {
        	left++;
        }
        
        if (left >= right) {
        	return 0;
        }
        
        while (right > left && nums[right] >= nums[right-1]) {
        	right--;
        }
        
        int max = nums[left];
        int min = nums[left];
        for (int i = left + 1; i <= right; i++) {
        	max = Math.max(max, nums[i]);
        	min = Math.min(min, nums[i]);
        }
        
        int s = left;
        int e = right;
        for (int i = 0; i < left; i++) {
        	if (nums[i] > min) {
        		s = i;
        		break;
        	}
        }
        
        for (int i = nums.length - 1; i >right; i--) {
        	if (nums[i] < max) {
        		e = i;
        		break;
         	}
        }
        
        return e - s + 1;
    
    }
    

    }


Log in to reply
 

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