LeetCode Russian Doll Envelopes

本文探讨了俄罗斯套娃信封问题的解决方案,通过特定排序和最长递增子序列算法求解最大数量的信封组合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description:

You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope.

What is the maximum number of envelopes can you Russian doll? (put one inside other)


Solution:

将weight从小打到排序,一样的weight就按照height从大到小排序。然后将height单独拿出来,求LIS即可。


import java.util.Arrays;

class Envelop implements Comparable<Envelop> {
	int width;
	int height;

	Envelop(int w, int h) {
		this.width = w;
		this.height = h;
	}

	public int compareTo(Envelop o) {
		if (this.width == o.width)
			return o.height - this.height;
		return this.width - o.width;
	}
}

public class Solution {
	public int maxEnvelopes(int[][] envelopes) {
		int len = envelopes.length;
		if (len == 0)
			return 0;
		Envelop[] arr = new Envelop[len];
		for (int i = 0; i < len; i++)
			arr[i] = new Envelop(envelopes[i][0], envelopes[i][1]);
		Arrays.sort(arr);
		int index = 1;
		int[] dp = new int[len];
		dp[0] = arr[0].height;
		for (int i = 1; i < len; i++) {
			if (arr[i].height > dp[index - 1]) {
				dp[index++] = arr[i].height;
			} else {
				int left = 0;
				int right = index - 1;
				int mid = left;
				while (left < right) {
					mid = (left + right) / 2;
					if (dp[mid] < arr[i].height) {
						left = mid + 1;
					} else {
						right = mid;
					}
				}
				dp[left] = arr[i].height;
			}
		}

		return index;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值