2019-09-14 23:16:25
总体感受:节奏尚可,难度尚可。然而还是卡在了最后一题,完全没有想到使用dp。
注意点:
1)Contest的最后一题往往是DP,Graph,这个敏感度需要提高;
2)DP的题目还是远远不够熟练。
- 801. Minimum Swaps To Make Sequences Increasing
问题描述:
问题求解:
keep[i] : 保留i位置的数字,使得[0, i]两个数组递增的最小交换次数。
swap[i] : 交换i位置的数字,使得[0, i]两个数组递增的最小交换次数。
public int minSwap(int[] A, int[] B) {
int n = A.length;
int[] keep = new int[n];
int[] swap = new int[n];
Arrays.fill(keep, n);
Arrays.fill(swap, n);
keep[0] = 0;
swap[0] = 1;
for (int i = 1; i < n; i++) {
if (A[i] > A[i - 1] && B[i] > B[i - 1]) keep[i] = Math.min(keep[i], keep[i - 1]);
if (A[i] > B[i - 1] && B[i] > A[i - 1]) keep[i] = Math.min(keep[i], swap[i - 1]);
if (B[i] > A[i - 1] && A[i] > B[i - 1]) swap[i] = Math.min(swap[i], keep[i - 1] + 1);
if (B[i] > B[i - 1] && A[i] > A[i - 1]) swap[i] = Math.min(swap[i], swap[i - 1] + 1);
}
return Math.min(keep[n - 1], swap[n - 1]);
}
- 1187. Make Array Strictly Increasing
问题描述:
问题求解:
public int makeArrayIncreasing(int[] arr1, int[] arr2) {
int n = arr1.length;
int[] keep = new int[n];
Set<Integer> set = new TreeSet<>();
for (int num : arr2) set.add(num);
int m = set.size();
int[] sorted = new int[m];
int idx = 0;
for (int num : set) sorted[idx++] = num;
int[] swap = new int[m];
Arrays.fill(keep, n + 1);
keep[0] = 0;
for (int i = 0; i < m; i++) swap[i] = 1;
for (int i = 1; i < n; i++) {
if (arr1[i] > arr1[i - 1]) keep[i] = keep[i - 1];
int cur_min = n;
for (int j = 0; j < m; j++) {
int cur_swap = n + 1;
if (arr1[i] > sorted[j]) keep[i] = Math.min(keep[i], swap[j]);
int temp = cur_min;
cur_min = Math.min(cur_min, swap[j]);
if (sorted[j] > arr1[i - 1]) cur_swap = Math.min(cur_swap, keep[i - 1] + 1);
cur_swap = Math.min(cur_swap, temp + 1);
swap[j] = cur_swap;
}
}
int res = Math.min(n + 1, keep[n - 1]);
for (int i = 0; i < m; i++) res = Math.min(res, swap[i]);
return res > n ? -1 : res;
}