forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
increasing-triplet-subsequence.py
55 lines (47 loc) · 1.4 KB
/
increasing-triplet-subsequence.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Time: O(n)
# Space: O(1)
# Given an unsorted array return whether an increasing
# subsequence of length 3 exists or not in the array.
# Formally the function should:
# Return true if there exists i, j, k
# such that arr[i] < arr[j] < arr[k]
# given 0 <= i < j < k <= n-1 else return false.
# Your algorithm should run in O(n) time complexity and O(1) space complexity.
# Examples:
# Given [1, 2, 3, 4, 5],
# return true.
# Given [5, 4, 3, 2, 1],
# return false.
class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
min_num, a, b = float("inf"), float("inf"), float("inf")
for c in nums:
if min_num >= c:
min_num = c
elif b >= c:
a, b = min_num, c
else: # a < b < c
return True
return False
# Time: O(n * logk)
# Space: O(k)
# Generalization of k-uplet.
class Solution_Generalization(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
def increasingKUplet(nums, k):
inc = [float('inf')] * (k - 1)
for num in nums:
i = bisect.bisect_left(inc, num)
if i >= k - 1:
return True
inc[i] = num
return k == 0
return increasingKUplet(nums, 3)