-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path334 Increasing Triplet Subsequence.py
58 lines (46 loc) · 1.24 KB
/
334 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
"""
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.
Author: Rajeev Ranjan
"""
import sys
class Solution(object):
def increasingTriplet(self, nums):
"""
Brute force: O(N^3)
dp: O(N)
:type nums: List[int]
:rtype: bool
"""
min1 = sys.maxint
min2 = sys.maxint
for e in nums:
if e < min1:
min1 = e
elif e != min1 and e < min2:
min2 = e
elif e > min2:
return True
return False
def increasingTripletError(self, nums):
"""
use stack
:type nums: List[int]
:rtype: bool
"""
stk = []
for elt in nums:
while stk and stk[-1] >= elt:
stk.pop()
stk.append(elt)
if len(stk) >= 3:
return True
return False