LeetCode 646. Maximum Length of Pair Chain (Medium)
You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.
Now, we define a pair (c, d) can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion.
Given a set of pairs, find the length longest chain which can be formed. You needn't use up all the given pairs. You can select pairs in any order.
Example 1:
Input: [[1,2], [2,3], [3,4]] Output: 2 Explanation: The longest chain is [1,2] -> [3,4]
Note:
- The number of given pairs will be in the range [1, 1000].
方法一: stack
思路:把array根据first number和second number从小到大排序
1 维护一个递增栈,栈里存放着的是每一个pair。
2 如果一个pair的first number比栈顶的second number大,那么直接把这个pair加进来。
3 否则如果这个pair的first number比栈顶的second number相等,那么我们直接把这个pair pass掉。
4 如果pair的first number比栈顶的second number大,那么我们弹栈一直到这个栈顶的second number比pair的second number小,然后把这个新的pair加进来。但要注意的是需要判断
是否有弹栈的行为。有弹栈,我们再加pair.
time complexity: O(nlogn) space complexity: O(n)
class Solution: def findLongestChain(self, pairs: List[List[int]]) -> int: if not pairs or len(pairs) == 0: return 0 pairs.sort(key = lambda x:(x[0], x[1])) # print(pairs) stack = [] stack.append(pairs[0]) for i in range(1, len(pairs)): cur = pairs[i] pre = stack[-1] if cur[0] > pre[1]: stack.append(cur) elif cur[0] == pre[1]: continue else: shouldAppend = False while stack and stack[-1][1] > cur[1]: stack.pop() shouldAppend = True if shouldAppend: stack.append(cur) #print(stack) return len(stack)
方法二:greedy
思路:把数组按照second number排序。
1 用两个变量 cur保存当前second number,res保存可以形成的length
2 遍历数组。如果遇到数组的first number比cur大,cur update成这个pair的second number。res+= 1。
time complexity:O(nlogn) space complexity:O(1)
class Solution: def findLongestChain(self, pairs: List[List[int]]) -> int: if not pairs or len(pairs) == 0: return 0 pairs.sort(key = lambda x:(x[1])) cur = float('-inf') res = 0 for pair in pairs: if cur < pair[0]: cur = pair[1] res += 1 return res
方法三:dp
class Solution(object): #Time Limit Exceeded def findLongestChain(self, pairs): pairs.sort() dp = [1] * len(pairs) for j in xrange(len(pairs)): for i in xrange(j): if pairs[i][1] < pairs[j][0]: dp[j] = max(dp[j], dp[i] + 1) return max(dp)
浙公网安备 33010602011771号