Find the second smallest number in a list using recursion

后端 未结 6 1944
故里飘歌
故里飘歌 2021-02-19 18:08

I know there has been a question asked on this topic, but none of the answers have helped me. I don\'t need help with implementing the code, I just need help sorting through the

6条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-19 18:39

    You can use classical divide and conquer. Let f(x) be a function that returns a tuple (a,b) containing the smallest and next smallest elements in list x.

    The base cases are when x has 0 or 1 elements. Beyond the base case, split the list in 2, recur to find the least two elements of each half, then pick the least 2 of these 4 as the result:

    def min2(x):
      if len(x) == 0: return sys.maxsize, sys.maxsize
      if len(x) == 1: return x[0], sys.maxsize
      m = int(len(x)/2)
      a1, b1 = min2(x[:m])
      a2, b2 = min2(x[m:])
      return (a1, min(b1, a2, b2)) if a1 < a2 else (a2, min(b2, a1, b1))
    
    def secondSmallest(x)
      return min2(x)[1]
    

    Here I'm using sys.maxsize as "infinity."

提交回复
热议问题