O(nlogn) Java Solution


  • 0
    W

    The idea is to sort the array and compare sorted array with the original array and checks the start and end index for the difference subarray.

    public int findUnsortedSubarray(int[] nums) {
    	int[] sorted = new int[nums.length];
    	for (int i = 0; i < nums.length; i++) {
    		sorted[i] = nums[i];
    	}
    	Arrays.sort(sorted);
    	int start = 0;
    	int end = nums.length - 1;
    	while (start < nums.length && sorted[start] == nums[start]) {
    		start++;
    	}
    	while (end >= 0 && sorted[end] == nums[end]) {
    		end--;
    	}
    	if (end < start)
    		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.