題目鏈接:https://leetcode-cn.com/problems/shu-zu-zhong-de-ni-xu-dui-lcof/
題目描述
在數組中的兩個數字,如果前面一個數字大於後面的數字,則這兩個數字組成一個逆序對。輸入一個數組,求出這個數組中的逆序對的總數。
第一次編輯代碼:
class Solution {
public int reversePairs(int[] nums) {
int ans = 0;
int n = nums.length;
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
if(nums[i] > nums[j])
ans++;
return ans;
}
}
提交結果
超出時間限制。
反思
果然,看了下這道題應該用歸併。