20190901拼多多和腾讯

跟風遠走 提交于 2020-02-22 17:52:22

好几道排序的题目

PDD(手机里有题目)

 

# 优先偶数的有序TopN(AC)
def QuickSort(array,left,right):
    # 递归的退出条件
    if left >= right:
        return
     
    temp = array[left]
    i = left
    j = right
    while i<j:
        while array[j]>temp and i<j:
            j -= 1
        if array[j]<temp:
            array[i] = array[j]
            i += 1
        while array[i]<temp and i<j:
            i += 1
        if array[i]>temp:
            array[j] = array[i]
            j -= 1
    array[i] = temp
    QuickSort(array,left,i-1)
    QuickSort(array,i+1,right)

def topN(lst,N):
    lst_a = []
    lst_b = []
    for item in lst:
        if item%2 == 0:
            lst_a.append(item)
        if item%2 != 0:
            lst_b.append(item)
    print("偶数:",lst_a)
    print("奇数:",lst_b)
    QuickSort(lst_a,0,len(lst_a)-1)
    QuickSort(lst_b,0,len(lst_b)-1)
    lst_a = lst_a[::-1]
    lst_b = lst_b[::-1]
    lst_a.extend(lst_b)
    res = lst_a[:N] 
    return ",".join([str(x) for x in res])

if __name__ == "__main__":
    lst,n = input().split(";")
    lst = list(map(int,lst.split(",")))
    N = int(n)
    print(lst)
    print(topN(lst,N))

 腾讯记得第一题AC了(图在对象那里)

# 优先偶数的有序TopN
def QuickSort(array,left,right):
    # 递归的退出条件
    if left >= right:
        return
     
    temp = array[left]
    i = left
    j = right
    while i<j:
        while array[j]>temp and i<j:
            j -= 1
        if array[j]<temp:
            array[i] = array[j]
            i += 1
        while array[i]<temp and i<j:
            i += 1
        if array[i]>temp:
            array[j] = array[i]
            j -= 1
    array[i] = temp
    QuickSort(array,left,i-1)
    QuickSort(array,i+1,right)

def topN(lst,N):
    lst_a = []
    lst_b = []
    for item in lst:
        if item%2 == 0:
            lst_a.append(item)
        if item%2 != 0:
            lst_b.append(item)
    print("偶数:",lst_a)
    print("奇数:",lst_b)
    QuickSort(lst_a,0,len(lst_a)-1)
    QuickSort(lst_b,0,len(lst_b)-1)
    lst_a = lst_a[::-1]
    lst_b = lst_b[::-1]
    lst_a.extend(lst_b)
    res = lst_a[:N] 
    return ",".join([str(x) for x in res])

if __name__ == "__main__":
    lst,n = input().split(";")
    lst = list(map(int,lst.split(",")))
    N = int(n)
    print(lst)
    print(topN(lst,N))

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!