Increasing Triplet Subsequence
Problem: Increasing Triplet Subsequence
At first, I consider to use a triplet to store the subsequence. If we find a smaller number which is good to improve the possibility of a result, we can do swapping. One idea is that we can do swapping if there is one number currently in the triplet or store the smaller number in a backup if there are currently two numbers in the triplet.
Code in Python:
class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) < 3: return False
triplet = []
_triplet = []
for i in xrange(len(nums)):
if len(triplet) == 0:
triplet.append(nums[i])
elif len(triplet) == 1:
if nums[i] > triplet[0]: triplet.append(nums[i])
else: triplet[0] = nums[i]
else:
if triplet[1] < nums[i]: return True
elif nums[i] <= triplet[1] and nums[i] > triplet[0]: triplet[1] = nums[i]
else:
while _triplet and nums[i] <= _triplet[-1]:
_triplet.pop()
_triplet.append(nums[i])
if len(_triplet) == 2: triplet = _triplet
return False
However, if we are storing [1,2] in the triplet and meet with -1 for example, we can just swap 1 with -1 and don't interfere with the result. So there's a much better solution here.