题解 | #计算数组的小和#

计算数组的小和

http://www.nowcoder.com/practice/edfe05a1d45c4ea89101d936cac32469

n = int(input())
nums = list(map(int, input().split()))
def merge_sort(left, right):
    if left >= right:
        return 0
    m = (left + right) // 2
    res = merge_sort(left, m) + merge_sort(m + 1, right)
    i, j = left, m + 1
    temp = [0] * (right - left + 1)
    index = 0
    while i <= m and j <= right:
        if nums[i] <= nums[j]:
            res += nums[i] * (right - j + 1)
            temp[index] = nums[i]
            index += 1
            i += 1
        else:
            temp[index] = nums[j]
            j += 1
            index += 1
    while j < right + 1 or i < m + 1:
        if i < m + 1:
            temp[index] = nums[i] 
            i += 1
        else:
            temp[index] = nums[j]
            j += 1
        index += 1
    nums[left:right + 1] = temp
        
    return res
print(merge_sort(0, len(nums) - 1))
全部评论

相关推荐

不愿透露姓名的神秘牛友
11-27 10:48
点赞 评论 收藏
分享
努力学习的小绵羊:我反倒觉得这种挺好的,给不到我想要的就别浪费大家时间了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务