leetcode小白刷题之旅----674. Longest Continuous Increasing Subsequence
仅供自己学习
题目:
Given an unsorted array of integers nums, return the length of the longest continuous increasing subsequence (i.e. subarray). The subsequence must be strictly increasing.
A continuous increasing subsequence is defined by two indices l and r (l < r) such that it is [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] and for each l <= i < r, nums[i] < nums[i + 1].
思路:
1.之前写过的 编号为3,求最长子串长度的题学到了一个滑动窗口的算法。看到这题 感觉比较类似也可以使用。但是存在一点差别,我用到unordered_map <int,int> m是以nums[ i ]为key和value,并且创建一个last用来比较是否为递增,其值为子数列最右元素的前一个元素。因为题目给出的数据范围是 -10^9 到10^9 ,为了保证第一个元素为最小值时也能正确比较,将m[last]=-10^10即可。其余与滑动窗口算法相同,当不为递增后,就移动left到右tag所指位置的前一个元素的位置,长度仍可用 i-left获得。
代码:
1 class Solution { 2 public: 3 int findLengthOfLCIS(vector<int>& nums) { 4 unordered_map <int,int> m; 5 int left=-1,last=-1; 6 int maxlen=0; 7 m[last]=-1000000000; 8 for(int i=0;i<nums.size();) 9 { 10 m[nums[i]] = nums[i]; 11 if(m[nums[i]]>m[last] ) 12 { 13 maxlen=max(maxlen,i-left); 14 last = nums[i++]; 15 } 16 else 17 { 18 left=i-1; 19 last = nums[i++]; 20 } 21 22 } 23 return maxlen; 24 } 25 };