java 套娃_【leetcode编程题目354】俄罗斯套娃
來(lái)自?https://leetcode.com/problems/russian-doll-envelopes/
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)
Example:
Given envelopes =?[[5,4],[6,4],[6,7],[2,3]], the maximum number of envelopes you can Russian doll is?3?([2,3] => [5,4] => [6,7]).
這個(gè)題目是最長(zhǎng)子序列的變形;最長(zhǎng)子序列可以參考https://en.wikipedia.org/wiki/Longest_increasing_subsequence
本題目的解法:
1. 先將長(zhǎng)方形按照寬排序,如果寬度一樣, 按照高度降序排列,即 wi < wj or wi == wj && hi > hj; 這樣得到的序列,從寬度考慮,前面的肯定可以放入后面的;對(duì)于wi == wj && hi > hj是因?yàn)樵趯挾纫恢碌那闆r下,將更高的放在前面,可以保證后面根據(jù)高度查找最長(zhǎng)子序列的時(shí)候,將這種組合排除;
2. 然后根據(jù)高度查找可以嵌套的最長(zhǎng)子序列即可;
func maxEnvelopes(envelopes [][]int) int {
sort.Sort(byShape(envelopes))
m := make([]int, len(envelopes)+1, len(envelopes)+1)
L := 0
for i, a := range envelopes {
lo, hi := 1, L
for lo <= hi {
mid := (lo + hi) / 2
b := envelopes[m[mid]]
if b[1] < a[1] {
lo = mid + 1
} else {
hi = mid - 1
}
}
m[lo] = i
if L < lo {
L = lo
}
}
return L
}
type byShape [][]int
func (a byShape) Len() int {
return len(a)
}
func (a byShape) Less(i, j int) bool {
if a[i][0] != a[j][0] {
return a[i][0] < a[j][0]
}
return a[j][1] < a[i][1]
}
func (a byShape) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
總結(jié)
以上是生活随笔為你收集整理的java 套娃_【leetcode编程题目354】俄罗斯套娃的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java if and_关于java:i
- 下一篇: java 登录踢出_spring sec