第十二周(Consecutive)
目录:
- 本周完成题目
- 主要过程思路
- 相关代码
一、本周完成题目
本周共完成2道题目,1道Hard,1道Easy。本周所学的线性规划没有找到直接的相关题目,所以随便选择了两道关于Consecutive的题目进行练习。
具体完成题目及难度如下表:
# | Title | Difficulty |
---|---|---|
128 | Longest Consecutive Sequence | Hard |
485 | Max Consecutive Ones | Easy |
题目内容
1、Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
题目大意:给定一个未排序数组,找到最长连续的元素子序列长度,时间复杂度需要为O(n)。
2、Max Consecutive Ones
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.The maximum number of consecutive 1s is 3.
Note:
The input array will only contain 0 and 1.
The length of input array is a positive integer and will not exceed 10,000
题目大意:给一个只有0,1组成的数组,判断1连续出现的最大长度。
二、主要过程思路
1、Longest Consecutive Sequence:
本题中我使用到了map,便于查找对应数字。map m中存储了数字和数字对应的连续长度。
对于数组进行遍历。每次访问m[i],如果m[i]访问过则跳过。未访问过则访问m[i-1]和m[i+1],将这两个数字相加后+1即可以得到m[i]的值。令m[i]与res对比,留下较大的值作为新的res。
同时, m[i-left]=m[i],m[i+right]=m[i],这是可以出现过的数字串的数字开头和末尾位置,对于开头末尾进行修正。
最后返回最大的res即为所求结果。
2、Max Consecutive Ones:
本题比较简单,只需要遍历一次数组。对于每个连续的1的数字段记录长度,如果遇到0则终止数字段开始下一个数字段。
具体来说,设定一个res用于表示结果,maxtmp表示当前的连续1的长度。从第一个数字开始遍历,如果遇到1就令maxtmp+1,如果遇到0就比较maxtmp和res的大小,取较大的赋值给res并同时将maxtmp置零。最后返回的res即为结果。
三、相关代码
Longest Consecutive Sequence
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_map<int, int> m;
int res = 0;
for (int i : nums){
if(m[i]) continue;
int left=m[i-1];
int right=m[i+1];
m[i]=left+right+1;
res=max(res,m[i]);
m[i-left]=m[i];
m[i+right]=m[i];
}
return res;
}
};
Max Consecutive Ones
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int maxtmp=0,res=0;
for(int i=0;i<nums.size();i++){
if(nums[i]==1){
maxtmp+=1;
}
else{
res=max(maxtmp,res);
maxtmp=0;
}
}
res=max(maxtmp,res);
return res;
}
};