Leetcode: Reverse pair

Reverse Pair

Topic

Calculate the amount of reverse pair in a int array. And the definition of reverse pair is satisfied with this condition: nums[i] > 2 * nums[j].

Steps of analysis

  1. Use Merge Sort.
  2. Merge Sort has two main steps. Firstly, deviding the array into two sub array. Secondly, when recursive to the bottom, return to the top, merge two sub array.
  3. we calculate the amount of reverse pair during the second step of merge sort. Defined two pointer i, j, point to each begin of sub array. and move j until nums[i] ≤ 2 * nums[j], that means we found a group of reverse pair, which is j - mid - 1.
  4. in the end, the total amount of pairs is in left array plus right array for the reverse pair.

Code

package Recursiona
fun main() {
    ReversePair().reversePairs()
}

class ReversePair {
    fun reversePairs() {
        val nums = intArrayOf(2147483647,2147483647,-2147483647,-2147483647,-2147483647,2147483647)
        val aux = IntArray(nums.size)
        val count = mergeSort(nums, 0, nums.size - 1, aux)
        print("count = $count")
    }

    fun mergeSort(nums: IntArray, lo: Int, hi: Int, aux: IntArray): Int {
        if(lo == hi) {
            return 0
        }
        val mid = lo + (hi - lo) / 2
        val l = mergeSort(nums, lo, mid, aux)
        val r = mergeSort(nums, mid + 1, hi, aux)
        var ret = l + r

        //cal amount of reverse pair between left array and right array.
        var i = lo
        var j = mid + 1
        while (i <= mid) {
            //[2, 3, 8] [0, 1, 5]

            //move j to the left util meet nums[i] <= 2 * nums[j]
            while (j <= hi && nums[i].toLong() > 2 * (nums[j] .toLong())) {
                j++
            }
            // [2,0][2, 1] are reverse pair.
            ret += j - mid - 1

            i++ // continue to move point i to the right.
        }
        //merge those array
        merge(nums, lo, mid, hi, aux)
        return ret
    }

    private fun merge(nums: IntArray, lo: Int, mid: Int, hi: Int, aux: IntArray) {
        //copy to aux
        for (i in lo..hi) {
            aux[i] = nums[i]
        }

        //copy ordered aux to nums
        var k = lo
        var i = lo
        var j = mid + 1
        while (i <= mid && j <= hi) {
            if (aux[i] <= aux[j]) {
                nums[k] = aux[i]
                i++
                k++
            } else {
                nums[k] = aux[j]
                j++
                k++
            }
        }

        while (i <= mid) {
            nums[k] = aux[i]
            i++
            k++
        }

        while (j <= hi) {
            nums[k] = aux[j]
            j++
            k++
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值