Swift solution - O(n) time, Sort


  • 0
    class Solution {
        func findUnsortedSubarray(_ nums: [Int]) -> Int {
            let n = nums.count
            var start = -1
            var end = -2
            var minNum = nums[n - 1]
            var maxNum = nums[0]
            
            for i in 1..<n {
                maxNum = max(maxNum, nums[i])
                minNum = min(minNum, nums[n - 1 - i])
                if nums[i] < maxNum {
                    end = i
                }
                if nums[n - 1 - i] > minNum {
                    start = n - 1 - i
                }
            }
            
            return end - start + 1
        }
        
        func findUnsortedSubarray_Sort(_ nums: [Int]) -> Int {
            let n = nums.count
            let temp = nums.sorted()
            var start = 0
            var end = n - 1
            
            while start < n && nums[start] == temp[start] {
                start += 1
            }
            while end > start && nums[end] == temp[end] {
                end -= 1
            }
            
            return end - start + 1
        }
    }
    

Log in to reply
 

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