《LeetCode笔记62》:数组中的逆序对

Python3.8

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

题目:

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。

示例 1:

输入: [7,5,6,4]
输出: 5

限制:

  • 0 <= 数组长度 <= 50000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof

方法一:归并排序

在排序中计数,如果有前后两段排序好的序列,记录后段序列的各个元素越过前段序列元素个数的和,为逆序数。

class Solution:
    def reversePairs(self, nums: List[int]) -> int:
        l = len(nums)
        if l<2:
            return 0
        counting, nums = self.sort_partiton(nums)
        print(nums)
        return counting

    def sort_partiton(self, nums):
        sort_counting = 0
        l = len(nums)
        if l == 2:
            if nums[0]>nums[1]:
                sort_counting+=1
                c = nums[0]
                nums[0]=nums[1]
                nums[1]=c
            return sort_counting, nums
        elif l < 2:
            return 0,nums
        else:
            middle = l//2
            x1, nums1 = self.sort_partiton(nums[0:middle])
            x2, nums2 = self.sort_partiton(nums[middle:l])
            sort_counting += x1
            sort_counting += x2
            l1 = middle
            l2 = l-middle
            i = 0
            j = 0
            for n in range(l):
                if nums1[i]<=nums2[j]:
                    nums[n] = nums1[i]
                    i+=1
                else:
                    nums[n] = nums2[j]
                    j+=1
                    sort_counting += (l1-i)
                if i==l1 or j==l2:
                    break
            if i==l1:
                nums[n+1:] = nums2[j:]
            elif j==l2:
                nums[n+1:] = nums1[i:]
            return sort_counting, nums

 

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值