674. Longest Continuous Increasing Subsequence
solved at 2019.12.25
Given an unsorted array of integers, find the length of longest continuous
increasing subsequence (subarray).
Example 1:
Input: [1,3,5,4,7]
Output: 3
Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.
Even though [1,3,5,7] is also an increasing subsequence, it's not a continuous one where 5 and 7 are separated by 4.
Example 2:
Input: [2,2,2,2,2]
Output: 1
Explanation: The longest continuous increasing subsequence is [2], its length is 1.
Note: Length of the array will not exceed 10,000.
Solution:
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
_max = 0
L = 0
for R in range(len(nums)):
if (R + 1) == len(nums) or nums[R+1] <= nums[R]:
_max = max(_max, (R + 1 - L))
L = R + 1
return _max
Submit:
Runtime: 80 ms, faster than 79.26% of Python3 online submissions for Longest Continuous Increasing Subsequence.
Memory Usage: 13.9 MB, less than 95.65% of Python3 online submissions for Longest Continuous Increasing Subsequence.
830. Positions of Large Groups
solved at 2019.12.25
In a string S
of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like S = "abbxxxxzyy"
has the groups "a"
, "bb"
, "xxxx"
, "z"
and "yy"
.
Call a group large if it has 3 or more characters. We would like the starting and ending positions of every large group.
The final answer should be in lexicographic order.
Example 1:
Input: "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the single large group with starting 3 and ending positions 6.
Example 2:
Input: "abc"
Output: []
Explanation: We have "a","b" and "c" but no large group.
Example 3:
Input: "abcdddeeeeaabbbcd"
Output: [[3,5],[6,9],[12,14]]
Note: 1 <= S.length <= 1000
Solution:
class Solution:
def largeGroupPositions(self, S: str) -> List[List[int]]:
ans = []
slow = 0
for fast in range(0, len(S)):
if fast == len(S) - 1 or S[fast+1] != S[slow]:
if ((fast + 1) - slow) >= 3:
ans.append([slow, fast])
slow = fast + 1
return ans
说明:
line 6: 为了包含 […, ‘b’, ‘f’, ‘f’, ‘f’] 的情况能使用x-y >= 3
判断,则需要使用 S[fast+1] 与 S[slow] 比较。line 6: 为了使用 S[fast+1],不会超出数组长度,if + or 判断短路运算,判断是否超出在先。
line 9: 从 line 4 就确定的 slow 是指向待比较的那一位,第一次开始
fast === slow
,这样才能保证第一个比较是slow + 1 == slow
。
Reference
n/a