Finding the second smallest integer in array

后端 未结 19 2248
無奈伤痛
無奈伤痛 2021-01-18 05:48

We are required in our assignment to find the second smallest integer in one array recursively. However, for the sake of understanding the subject more, I want to do it iter

19条回答
  •  庸人自扰
    2021-01-18 06:19

    You can do it in O(n) time. Below is the python code

    def second_small(A):
        if len(A)<2:
            print 'Invalid Array...'
            return
        small = A[0]
        second_small = [1]
        if small >  A[1]:
            second_small,small = A[0],A[1]
    
        for i in range(2,len(A)):
            if A[i] < second_small and A[i]!=small:
                if A[i] < small:
                    second_small = small
                    small = A[i]
                else:
                    second_small = A[i]
        print small, second_small
    A = [12, 13, 1, 10, 34, 1]
    second_small(A)
    

提交回复
热议问题