1.
其实就是在归并排序中,添加几行代码。首先归并排序的原理,其次是加的这几行代码的意义。
class Solution {
public int reversePairs(int[] nums) {
if(nums == null || nums.length <= 2) return 0;
return Mergesort(nums,0,nums.length-1);
}
//归并排序
public int Mergesort(int [] a,int left,int right){
if(left == right) return 0 ;
int center = (left+right)/2;
int leftcount = Mergesort(a,left,center);//左半边
int rightcount = Mergesort(a,center+1,right);//右半边
int brigecount = merge(a,left,center,right);
return leftcount + rightcount + brigecount;
}
private int merge (int[] a,int leftPos,int center,int rightEnd){//创建一个最大堆
int[] tmp = new int[rightEnd - leftPos + 1];
int left = leftPos;
int count = 0;//用于记录逆序对数
int temPos =0;
int rightPos = center + 1;
int numElements = rightEnd - leftPos + 1;
while (leftPos<=center && rightPos<=rightEnd){
if(a[leftPos] <= a[rightPos]){
count += rightPos - (center + 1);
tmp[temPos++] = a[leftPos++];
}else {
tmp[temPos++] = a[rightPos++];
}
}
while (leftPos<=center){
count += rightPos - (center + 1);
tmp[temPos++] = a[leftPos++];
}
while (rightPos<=rightEnd){
tmp[temPos++] = a[rightPos++];
}
//tmp数组就已经按从小到大排序好了
for (int k = 0; k < tmp.length; k++) {
a[left + k] = tmp[k];
}
return count;
}
}
2.
这道题难度很大,得反复看。
class Solution {
public boolean isMatch(String A, String B) {
int n = A.length();
int m = B.length();
boolean[][] f = new boolean[n + 1][m + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
//分成空正则和非空正则两种
if (j == 0) {
f[i][j] = i == 0;
} else {
//非空正则分为两种情况 * 和 非*
if (B.charAt(j - 1) != '*') {
if (i > 0 && (A.charAt(i - 1) == B.charAt(j - 1) || B.charAt(j - 1) == '.')) {
f[i][j] = f[i - 1][j - 1];
}
} else {
//碰到 * 了,分为看和不看两种情况
//不看
if (j >= 2) {
f[i][j] |= f[i][j - 2];
}
//看
if (i >= 1 && j >= 2 && (A.charAt(i - 1) == B.charAt(j - 2) || B.charAt(j - 2) == '.')) {
f[i][j] |= f[i - 1][j];
}
}
}
}
}
return f[n][m];
}
}