Count of Smaller Numbers After Self

本文介绍了解决逆序数对问题的两种方法:通过改进的归并排序实现和利用二叉搜索树(BST)。这两种方法分别展示了如何在排序过程中统计逆序数对,并提供了一种更为直观的方法来解决该问题。


题目描述

You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

Example:

Given nums = [5, 2, 6, 1]

To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.

Return the array [2, 1, 1, 0].

题意理解

给一个数组nums,返回一个数组count,该数组i位置上的数是nums[i]右边比它大的数.
其实就是找每一个数的逆序数对的个数

MergeSort

这个方法很聪明,但是也很难,参考了网上的代码
算法思想:逆序数对其实就是归并排序中要交换位置的数对

参考资料

参考网站处的代码:

#include <bits/stdc++.h>

int  _mergeSort(int arr[], int temp[], int left, int right);
int merge(int arr[], int temp[], int left, int mid, int right);

/* This function sorts the input array and returns the
   number of inversions in the array */
int mergeSort(int arr[], int array_size) {
    int *temp = (int *)malloc(sizeof(int)*array_size);
    return _mergeSort(arr, temp, 0, array_size - 1);
}

/* An auxiliary recursive function that sorts the input array and
  returns the number of inversions in the array. */
int _mergeSort(int arr[], int temp[], int left, int right) {
  int mid, inv_count = 0;
  if (right > left) {
    /* Divide the array into two parts and call _mergeSortAndCountInv()
       for each of the parts */
    mid = (right + left)/2;

    /* Inversion count will be sum of inversions in left-part, right-part
      and number of inversions in merging */
    inv_count  = _mergeSort(arr, temp, left, mid);
    inv_count += _mergeSort(arr, temp, mid+1, right);

    /*Merge the two parts*/
    inv_count += merge(arr, temp, left, mid+1, right);
  }
  return inv_count;
}

/* This funt merges two sorted arrays and returns inversion count in
   the arrays.*/
int merge(int arr[], int temp[], int left, int mid, int right) {
  int i, j, k;
  int inv_count = 0;

  i = left; /* i is index for left subarray*/
  j = mid;  /* j is index for right subarray*/
  k = left; /* k is index for resultant merged subarray*/
  while ((i <= mid - 1) && (j <= right)) {
    if (arr[i] <= arr[j])
    {
      temp[k++] = arr[i++];
    }
    else
    {
      temp[k++] = arr[j++];

     /*this is tricky -- see above explanation/diagram for merge()*/
      inv_count = inv_count + (mid - i);
    }
  }

  /* Copy the remaining elements of left subarray
   (if there are any) to temp*/
  while (i <= mid - 1)
    temp[k++] = arr[i++];

  /* Copy the remaining elements of right subarray
   (if there are any) to temp*/
  while (j <= right)
    temp[k++] = arr[j++];

  /*Copy back the merged elements to original array*/
  for (i=left; i <= right; i++)
    arr[i] = temp[i];

  return inv_count;
}

/* Driver program to test above functions */
int main(int argv, char** args)
{
  int arr[] = {1, 20, 6, 4, 5};
  printf(" Number of inversions are %d \n", mergeSort(arr, 5));
  getchar();
  return 0;
}

我的解法

上面的代码跟需要的有所不同,需要更改,并且稍微有点晦涩,于是用自己的理解到的规律重新写了一种
在归并排序的时候有两个阶段,一个是排序,然后是归并,
1. 排序的时候,如果需要对调,那么对调的大的那个数就找到了一个更小数,所以大的那个数的result要+1
2. 归并的时候,如果右边和左边有一组数需要对调,说明右边有一个数比左边还没归并到的每个数都要小,说明左边还没归并到的每个数都找到了一个比自己小的数,所以计数器count+1,左边每个数归并到的时候result加上当时的count即可.
代码如下:

struct node {
    int data;
    int pos;
    node(int d, int p) {
        data = d;
        pos = p;
    }
};

class Solution {
public:    
    vector<int> countSmaller(vector<int>& nums) {
        vector<int> result(nums.size(), 0);
        vector<node> seq;
        for (int i = 0; i < nums.size(); i++)
            seq.push_back(node(nums[i], i));

        mergeSort(seq, result, 0, nums.size() - 1);
        return result;
    }

private:
    vector<node> mergeSort(vector<node>&seq, vector<int>& result, int l, int r) {
        // basic condition
        vector<node> temp;
        if (r < l) return temp;
        if (l == r) {
            temp.push_back(seq[l]);
            return temp;
        }
        if (r - l == 1) {
            if (seq[l].data > seq[r].data) {
                temp.push_back(seq[r]);
                temp.push_back(seq[l]);
                result[seq[l].pos]++;
            } else {
                temp.push_back(seq[l]);
                temp.push_back(seq[r]);
            }
            return temp;
        }

        // sort
        int mid = (r + l) / 2;
        vector<node> left = mergeSort(seq, result, l, mid);
        vector<node> right = mergeSort(seq, result, mid+1, r);

        //merge
        int count = 0;
        int i = 0, j = 0;
        while (i < left.size() || j < right.size()) {
            if (i >= left.size())  // the left is end
                while (j < right.size())
                    temp.push_back(right[j++]);
            else if (j >= right.size()) // the right is end
                while (i < left.size()) {
                    result[left[i].pos] += count;
                    temp.push_back(left[i++]);
                }

            else if (left[i].data > right[j].data) {
                count++;
                temp.push_back(right[j++]);
            } else {
                result[left[i].pos] += count;
                temp.push_back(left[i++]);
            }
        }
        return temp;

    }
};

开销 O(nlogn)

BST

相比mergesort更简洁易懂

class Solution {
public:
    struct Node {
        int val, smaller;
        Node *left, *right;
        Node(int value, int small) { 
            left=right=NULL, val=value, smaller=small; 
        }
    };

    int insert(Node *&root, int value) {
        if (root==NULL)
            return (root=new Node(value, 0)), 0;

        if (value < root->val) 
            return root->smaller++, insert(root->left, value);
        else
            return insert(root->right, value) + root->smaller + (value>root->val ? 1 : 0);
    }

    vector<int> countSmaller(vector<int>& nums) {
        Node *root = NULL;
        deque<int> ans;
        for (int i=nums.size()-1; i>=0; i--)
            ans.push_front(insert(root, nums[i]));

        return vector<int> (ans.begin(), ans.end());
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值