𝑰’𝒎 𝒉𝒉𝒈, 𝑰 𝒂𝒎 𝒂 𝒈𝒓𝒂𝒅𝒖𝒂𝒕𝒆 𝒔𝒕𝒖𝒅𝒆𝒏𝒕 𝒇𝒓𝒐𝒎 𝑵𝒂𝒏𝒋𝒊𝒏𝒈, 𝑪𝒉𝒊𝒏𝒂.
- 🏫 𝑺𝒉𝒄𝒐𝒐𝒍: 𝑯𝒐𝒉𝒂𝒊 𝑼𝒏𝒊𝒗𝒆𝒓𝒔𝒊𝒕𝒚
- 🌱 𝑳𝒆𝒂𝒓𝒏𝒊𝒏𝒈: 𝑰’𝒎 𝒄𝒖𝒓𝒓𝒆𝒏𝒕𝒍𝒚 𝒍𝒆𝒂𝒓𝒏𝒊𝒏𝒈 𝒅𝒆𝒔𝒊𝒈𝒏 𝒑𝒂𝒕𝒕𝒆𝒓𝒏, 𝑳𝒆𝒆𝒕𝒄𝒐𝒅𝒆, 𝒅𝒊𝒔𝒕𝒓𝒊𝒃𝒖𝒕𝒆𝒅 𝒔𝒚𝒔𝒕𝒆𝒎, 𝒎𝒊𝒅𝒅𝒍𝒆𝒘𝒂𝒓𝒆 𝒂𝒏𝒅 𝒔𝒐 𝒐𝒏.
- 💓 𝑯𝒐𝒘 𝒕𝒐 𝒓𝒆𝒂𝒄𝒉 𝒎𝒆:𝑽𝑿
- 📚 𝑴𝒚 𝒃𝒍𝒐𝒈: 𝒉𝒕𝒕𝒑𝒔://𝒉𝒉𝒈𝒚𝒚𝒅𝒔.𝒃𝒍𝒐𝒈.𝒄𝒔𝒅𝒏.𝒏𝒆𝒕/
- 💼 𝑷𝒓𝒐𝒇𝒆𝒔𝒔𝒊𝒐𝒏𝒂𝒍 𝒔𝒌𝒊𝒍𝒍𝒔:𝒎𝒚 𝒅𝒓𝒆𝒂𝒎
1-1:题目描述
在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
示例 1:
输入: [7,5,6,4]
输出: 5
限制:
0 <= 数组长度 <= 50000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1-2:利用归并排序
归并排序的核心思想是先分,再合,再将两两排序好的数组进行合并。归并排序讲解,我们可以利用合并的过程去解决这个问题。讲解视频中已经说的很清楚了,可以查看讲解视频,这里仅仅给出自己的代码以及注意点:
package com.company.xx.剑指offer.剑指Offer_51_数组中的逆序对;
public class Solution {
int[] temp;
int sum;
public int reversePairs(int[] nums) {
int n = nums.length;
this.temp = new int[n];
mergeSort(0, n - 1, nums);
return sum;
}
public void mergeSort(int low, int high, int[] nums) {
if (low < high) {
// 这边也容易写错,位移符号的优先级小
int mid = low + ((high - low) >> 1);
mergeSort(low, mid, nums);
mergeSort(mid + 1, high, nums);
merge(nums, low, mid, high);
}
}
public void merge(int[] nums, int low, int mid, int high) {
int lowIndex = low;
int highIndex = mid + 1; // 两个区间[low, mid];[mid+1, high]
int tempIndex = low; // 这是一个重要的地方,很容易写成0出错。
while (lowIndex <= mid && highIndex <= high) {
if (nums[lowIndex] <= nums[highIndex]) {
temp[tempIndex++] = nums[lowIndex++];
} else {
sum += (mid - lowIndex + 1);
temp[tempIndex++] = nums[highIndex++];
}
}
while (lowIndex <= mid) {
temp[tempIndex++] = nums[lowIndex++];
}
while (highIndex <= high) {
temp[tempIndex++] = nums[highIndex++];
}
// 将排序后的结果temp[low:high]拷贝回数组,以便下次merge继续使用
for (int i = low; i <= high; i++) {
nums[i] = temp[i];
}
}
public static void main(String[] args) {
int[] nums = new int[]{1, 2, 1, 2, 1};
Solution s = new Solution();
System.out.println(s.reversePairs(nums));
}
}