首页 > 其他分享 >LeetCode刷题记录.Day3

LeetCode刷题记录.Day3

时间:2022-11-01 23:24:32浏览次数:71  
标签:nums int sum subLength varLength Day3 指针 LeetCode 刷题

长度最小的子数组

题目链接209. 长度最小的子数组 - 力扣(LeetCode)

看似很简单。看完滑动窗口法的时候觉得很容易理解,时间复杂度O(n)的推导也理解。无非就是两个指针,因为题目要求子串必连续。

所以一个循环内嵌套一个慢指针,剔除大于目标值的部分

写的时候就漏了很多细节。第一次提交,条件判断错误。第二次提交,发现没考虑过输出的子串长度不是最小的情况。

最后提交的时候,漏掉了如果题目给出的数组所有值都不满足的情况。错了很多次,感觉自己在细节上还是没考虑周到,再接再厉。

不过双指针左右指针和快慢指针法倒是已经比较理解了

class Solution {
public:
    int minSubArrayLen(int target, vector<int>& nums) {
        int sum = 0;
        int subLength = INT32_MAX;
        int j = 0;
        for(int i = 0; i < nums.size(); i++){
            sum += nums[i];
            while(sum >= target){
                int varLength = (i - j + 1);
                if(varLength < subLength)
                    subLength = varLength;
                sum -= nums[j++];
            }
        }
        return subLength == INT32_MAX ? 0 : subLength;
    }
};

 

标签:nums,int,sum,subLength,varLength,Day3,指针,LeetCode,刷题
From: https://www.cnblogs.com/tianmaster/p/16849536.html

相关文章

  • 代码随想录day31 | 455.分发饼干 376. 摆动序列 53. 最大子序和
    455.分发饼干题目|文章思路满足能让最小胃口的孩子吃饱首先对饼干和胃口值都进行排序对饼干进行遍历,如果能满足当前孩子的胃口,那么就将结果加1。实现点击查看代......
  • leetcode-2423-easy
    RemoveLetterToEqualizeFrequencyYouaregivena0-indexedstringword,consistingoflowercaseEnglishletters.Youneedtoselectoneindexandremovethe......
  • leetcode-2144-easy
    MinimumCostofBuyingCandiesWithDiscountAshopissellingcandiesatadiscount.Foreverytwocandiessold,theshopgivesathirdcandyforfree.Thec......
  • leetcode-1460-easy
    MakeTwoArraysEqualbyReversingSubarraysYouaregiventwointegerarraysofequallengthtargetandarr.Inonestep,youcanselectanynon-emptysubarra......
  • leetcode-257-easy
    BinaryTreePathsGiventherootofabinarytree,returnallroot-to-leafpathsinanyorder.Aleafisanodewithnochildren.Example1:Input:root=......
  • leetcode-1304-easy
    FindNUniqueIntegersSumuptoZeroGivenanintegern,returnanyarraycontainingnuniqueintegerssuchthattheyaddupto0.Example1:Input:n=5O......
  • leetcode-118-easy
    Pascal'sTriangleGivenanintegernumRows,returnthefirstnumRowsofPascal'striangle.InPascal'striangle,eachnumberisthesumofthetwonumbersdir......
  • leetcode-1137-easy
    N-thTribonacciNumberTheTribonaccisequenceTnisdefinedasfollows:T0=0,T1=1,T2=1,andTn+3=Tn+Tn+1+Tn+2forn>=0.Givenn,returnthe......
  • 【HDLBits刷题笔记】12 More Circuits
    Rule90第一次见这东西有点莫名其妙,但是其实看懂了之后就是左移和右移相异或,注意这里使用的是逻辑右移,会自动补零,不能使用算数左移<<<。moduletop_module(inputcl......
  • 巧用hash; 双指针法 | 刷题第7天 | 454.四数相加II, 383. 赎金信, 15. 三数之和, 18.
    Problem:454.四数相加II思路讲述看到这一题的思路思考:如何用map有效节省时间想一想:题目1.两数之和,用的map推广:可以时间O(n^3),空间O(n)map:key=......