LeetCode Russian Doll Envelopes

来源:互联网 发布:mac os x 10.11正式版 编辑:程序博客网 时间:2024/05/17 03:30

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;}}


0 0
原创粉丝点击