【每日一题0710】奇数排序

哈利波特获得了一个数字列表,他的任务是必须将奇数按升序排序,同时将偶数保留在原来的位置。魔法师们,快来帮帮他吧~

题目难度:中等
题目来源:codewars

def sort_the_odd(nums):
    pass
    
assert sort_the_odd([7, 1]) == [1, 7]
assert sort_the_odd([5, 8, 6, 3, 4]) == [3, 8, 6, 5, 4]
assert sort_the_odd([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) == [1, 8, 3, 6, 5, 4, 7, 2, 9, 0]
def sort_the_odd(nums:list=None):
    """"""
    # print(nums)
    odd_number= sorted([n for n in nums if n%2!=0]) #过滤出奇数并排序
    for index in range(len(nums)):
        if nums[index]%2 != 0:#奇数
            nums[index] = odd_number[0] #将源列表中的奇数依次替换掉排好序的奇数
            odd_number.pop(0)
    return nums

def sort_the_odd2(nums:list=None):
    even_num = [(nums.index(num),num) for num in nums if num%2 == 0]  #拿源列表偶数的位置和值
    odd_number= sorted([n for n in nums if n%2!=0]) #过滤出奇数并排序
    for index,num in even_num:
        odd_number.insert(index,num)    #在奇数队列中插入偶数
    return odd_number

冒泡排序的升级版吗? 求简单解法。。。

def sort_the_odd(li):
    li_length=len(li)
    li1=[]
    li2=[]
    for i in range(li_length):
        if li[i]%2==1:
            li1.append(i)
            li2.append(li[i])

    for i in range(len(li2)-1):
        for j in range(len(li2)-1-i):
            if li2[j]>li2[j+1]:
                li2[j],li2[j+1]=li2[j+1],li2[j]
    for i in range(len(li2)):
        li[li1[i]]=li2[i]
    return li

题解:

def sort_the_odd(nums):
    odds = sorted(filter(lambda x:x % 2 == 1, nums))
    return [odds.pop(0) if item % 2 == 1 else item for i,item in enumerate(nums)]

assert sort_the_odd([7, 1]) == [1, 7]
assert sort_the_odd([5, 8, 6, 3, 4]) == [3, 8, 6, 5, 4]
assert sort_the_odd([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]) == [1, 8, 3, 6, 5, 4, 7, 2, 9, 0]

:partying_face: :partying_face: :partying_face: :partying_face: :partying_face: :partying_face:

@fwj 可以考虑把奇数单独拎出来排序好,然后遍历原列表替换成新顺序的元素,小型手术即可。

for (int i = 0; i < nums.length; i++) {
            if (nums[i] % 2 == 0) {
                continue;
            } else {
                for (int j = i; j < nums.length; j++) {
                    if ((nums[i] > nums[j]) &&(nums[j]%2 !=0)) {
                        int tmp = nums[i];
                        nums[i] = nums[j];
                        nums[j] = tmp;
                    }
                }
            }
        }