zoukankan      html  css  js  c++  java
  • Subarray sort

    refer to : https://www.algoexpert.io/questions/Subarray%20Sort

    Problem Statement

     Analysis

     

    Code

    def subarraySort(array):
        minOutOfOrder = float("inf")
        maxOutOfOrder = float("-inf")
        for i in range(len(array)):
            num = array[i]
            if isOutOfOrder(i, num, array):
                minOutOfOrder = min(minOutOfOrder, num)
                maxOutOfOrder = max(maxOutOfOrder, num)
        if maxOutOfOrder == float("-inf"):# or if minOutOfOrder == float("inf"), which means line 6 never has been hit, no unsorted values
            return [-1,-1]
        #check the correct position for the smallest valur of all the out of order values, from left to right
        subarrayLeftIdx = 0
        while minOutOfOrder >= array[subarrayLeftIdx]:
            subarrayLeftIdx += 1
        #check the correct position for the greatest valur of all the out of order values, from right to left
        subarrayRightIdx = len(array) - 1
        while maxOutOfOrder <= array[subarrayRightIdx]:
            subarrayRightIdx -= 1
        return [subarrayLeftIdx, subarrayRightIdx]
            
    # compare the current value to its two adjcent values
    # the first value has no left value, the last one has no right value
    def isOutOfOrder(i, num, array):
        if i == 0:
            return num > array[i + 1]
        if i == len(array) - 1:
            return num < array[i - 1]
        return num > array[i + 1] or num < array[i - 1]
        
     
  • 相关阅读:
    JOIN条件限制对结果记录的影响
    什么是linux?
    什么是操作系统?
    Internship settled!
    Python dict 调试技巧 —— 利用YAML存储dict内容
    c++ 异常处理
    C#可空类型
    C# 异常处理
    C#值类型与引用类型
    C# 类类型
  • 原文地址:https://www.cnblogs.com/LilyLiya/p/14835494.html
Copyright © 2011-2022 走看看