Java O(n) solution beats 100%


  • 0
    H
    class Solution {
    2
        public int findUnsortedSubarray(int[] nums) {
    3
            int begin = -1;
    4
            int end = -1;
    5
            int max = Integer.MIN_VALUE;
    6
            int index =1;
    7
            
    8
            for(int i = 0; i < nums.length; i++){
    9
                if(nums[i] >= max) {
    10
                    max = nums[i];
    11
                    index = i;
    12
                }
    13
                else{
    14
                    if(begin == -1) {
    15
                        begin = index;
    16
                        end = i;
    17
                    }
    18
                    else end = i;
    19
                    while(begin >= 1 && nums[begin-1] > nums[i]){
    20
                        begin--;
    21
                    }
    22
                    
    23
                }
    24
                
    25
            }
    26
            
    27
            return end==begin?0:end-begin+1;
    28
        }
    29
    }
    
    
    

Log in to reply
 

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