forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathincreasing-triplet-subsequence.py
62 lines (53 loc) · 1.52 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
56
57
58
59
60
61
62
# 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
"""
first_min, second_min = float("inf"), float("inf")
for i in nums:
if first_min >= i:
first_min, second_min = i, float("inf")
elif second_min >= i:
second_min = i
else:
return True
return False
# Time: O(n)
# Space: O(n)
class Solution2(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
n = len(nums)
exist_smaller = set()
min_num = 0
for i in xrange(1, n):
if (nums[i] <= nums[min_num]):
min_num = i
else:
exist_smaller.add(i)
max_num = n - 1
for i in reversed(xrange(n-1)):
if (nums[i] >= nums[max_num]):
max_num = i
else:
if i in exist_smaller:
return True
return False