Question
Leetcode - 面试题 17.08. Circus Tower LCCI
Train of thought
Sorting heights to be ascending order and weights to be descending order. dp[i] = j represents person[i] as the bottom of tower, the tower height is amount of j, to calculate the dp[i] we find the maximum of dp[0 ~ (i-1)] what the person[0 ~ (i-1)] shorter and lighter than person[i], increase it of one, it’s the dp[i] result.
class Solution {
public int bestSeqAtIndex(int[] height, int[] weight) {
int[][] persons = new int[height.length][2];
for (int i = 0; i < height.length; i++) {
persons[i][0] = height[i];
persons[i][1] = weight[i];
}
Arrays.sort(persons, (a, b) -> {
if (a[0] == b[0]) {
return b[1] - a[1];
}
return a[0] - b[0];
});
int[] dp = new int[persons.length];
Arrays.fill(dp, 1);
int max = 1;
for (int i = 1; i < persons.length; i++) {
for (int j = i - 1; j >= 0; j--) {
if (persons[j][1] < persons[i][1]) {
if (dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
}
}
}
if (dp[i] > max) {
max = dp[i];
}
}
return max;
}
}
Optimize
We can optimize the follow code, make it time complexity from O(n) to O(logn):
for (int j = i - 1; j >= 0; j--) {
if (persons[j][1] < persons[i][1]) {
if (dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
}
}
}
if (dp[i] > max) {
max = dp[i];
}
//-------------------- TO BE ------------------
left = 0; right = len;
while (left < right) {
mid = (left + right) / 2;
if (top[mid] > persons[i][1]) {
right = mid;
}
else if (top[mid] < persons[i][1]) {
left = mid + 1;
}
else {
right = mid;
}
}
if (left == len) {
len++;
}
top[left] = persons[i][1];
Following is the complete code文章来源:https://www.toymoban.com/news/detail-535503.html
class Solution {
public int bestSeqAtIndex(int[] height, int[] weight) {
int[][] persons = new int[height.length][2];
for (int i = 0; i < height.length; i++) {
persons[i][0] = height[i];
persons[i][1] = weight[i];
}
Arrays.sort(persons, (a, b) -> {
if (a[0] == b[0]) {
// using descending order to avoid choice twice person of the weights are equals,
// the principle is because of we choice the continuous top is ascending order
// and the heap is descending order, it can covered the ahead
return b[1] - a[1];
}
return a[0] - b[0];
});
int[] top = new int[persons.length];
int len = 0, left, right, mid;
for (int i = 0; i < persons.length; i++) {
left = 0; right = len;
while (left < right) {
mid = (left + right) / 2;
if (top[mid] > persons[i][1]) {
right = mid;
}
else if (top[mid] < persons[i][1]) {
left = mid + 1;
}
else {
right = mid;
}
}
if (left == len) {
len++;
}
top[left] = persons[i][1];
}
return len;
}
}
文章来源地址https://www.toymoban.com/news/detail-535503.html
到了这里,关于【每日一题】Leetcode - 面试题 17.08. Circus Tower LCCI的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!