-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem334.py
More file actions
50 lines (37 loc) · 1.12 KB
/
problem334.py
File metadata and controls
50 lines (37 loc) · 1.12 KB
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
'''
334. Increasing Triplet Subsequence
Medium
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.
Note: Your algorithm should run in O(n) time complexity and O(1) space complexity.
Example 1:
Input: [1,2,3,4,5]
Output: true
Example 2:
Input: [5,4,3,2,1]
Output: false
Solution:
Maintain two min value, when there's a number that is bigger than the two maintained min
value, simply return True.
At the end of iteration, return False since there is no pair.
'''
class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
min1 = min2 = max(nums)
for i in nums:
min1 = min(min1,i)
if i > min1:
min2 = min(min2,i)
if i > min2:
return True
return False
if __name__ == '__main__':
s = Solution()
nums = [3,2,1]
print s.increasingTriplet(nums)