Uncomfortable , Recently, it's really dynamic planning. When you see a problem, you think about dynamic planning first . I don't have the habit of analyzing time complexity , But today, when I saw the test example of Li Kou, I realized , want Analyze the worst time complexity
The idea of dynamic planning refers to “ The longest increasing subsequence ”, Use a one-dimensional list to record the status ,dp[n] Express nums[: n+1] The longest increasing subsequence length of , When you get the length > 3 Exit from time
Now given nums length n ( The scale of the problem ),if The statement will execute about , Time complexity O()
class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
dp = [1 for _ in range(len(nums))]
for cur in range(1, len(nums)):
cur_num = nums[cur]
# Record cur The number pointed to by the pointer
for last in range(cur):
if nums[last] < cur_num:
# When : last The number of the pointer < cur The number of the pointer
dp[cur] = max([dp[cur], dp[last] + 1])
# State shift
if dp[cur] >= 3:
return True
return False
The sample given by the test is very long , The assumption is [1, 2] * 4000 Well , The running time is 3.65 s
The greedy idea is : use p1 Points to the minimum value of the searched area , use p2 Points to the minor value of the searched area , These two values don't need to be in order
class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if len(nums) < 3:
return False
p1 = nums[0]
p2 = 1 << 32
# keep p1 < p2
for p3 in nums[1:]:
if p1 < p2 < p3:
return True
if p3 > p1:
p2 = min([p2, p3])
# p2 Take the minor value
else:
p1 = p3
# p1 Minimum value
return False
With [7, 6, 3, 4, 1, 2, 5] As an example, let's push it again
operation Read the values p3 minimum value p1 Second minimum p2 initialization 7inf166inf233inf34344114521265 (True)12Each read , Will choose Output 、 change p1、 change p2, That is to say p1 and p2 Will not change at the same time
The worst time complexity is from dynamic programming O() Down to the present O(n), nudges