第十二周(Consecutive)

第十二周(Consecutive)

目录:

  • 本周完成题目
  • 主要过程思路
  • 相关代码

一、本周完成题目

本周共完成2道题目,1道Hard,1道Easy。本周所学的线性规划没有找到直接的相关题目,所以随便选择了两道关于Consecutive的题目进行练习。

具体完成题目及难度如下表:

#TitleDifficulty
128Longest Consecutive SequenceHard
485Max Consecutive OnesEasy

题目内容

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;

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值