首页 > 其他分享 >代码随想录day31 | 455.分发饼干 376. 摆动序列 53. 最大子序和

代码随想录day31 | 455.分发饼干 376. 摆动序列 53. 最大子序和

时间:2022-11-01 22:46:47浏览次数:68  
标签:count nums int 复杂度 随想录 455 53 vector result

455.分发饼干

题目|文章
image

思路

满足能让最小胃口的孩子吃饱

  • 首先对饼干和胃口值都进行排序
  • 对饼干进行遍历,如果能满足当前孩子的胃口,那么就将结果加1。

实现

点击查看代码
class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());
        int result = 0;
        
        for(int i = 0; i < s.size(); i++) {
            if(result < g.size() && g[result] <= s[i]) {
                result++;
            }
        }
        return result;
    }
};

复杂度分析

  • 时间复杂度:O(nlogn),快速排序的复杂度为nlogn,遍历的复杂度为n,综合结果为nlogn。
  • 空间复杂度:O(1)

376. 摆动序列

题目|文章
image

思路

摆动序列的问题的解决方法在于取消掉连续增长和连续下降,只取峰值。对于两个端点的处理也是难点。

  • 默认右端点有一个峰值,然后从左端点开始遍历。
  • 在处理连续相等的值时,需要特殊考虑,只取一端。

实现

点击查看代码
class Solution {
public:
    int wiggleMaxLength(vector<int>& nums) {
        if(nums.size() <= 1) return nums.size();
        int prediff = 0;
        int curdiff = 0;
        int result = 1;
        for(int i = 0; i < nums.size() - 1; i++) {
            curdiff = nums[i+1] - nums[i];
            if((curdiff < 0 && prediff >= 0) || (curdiff > 0 && prediff <= 0)) {
                result ++;
                prediff = curdiff;
            }
           
        }
        return result;
    }
};

复杂度分析

  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

53. 最大子数组和

题目|文章
image

思路

局部最优:当连续子数组的和为负数时,立即舍弃当前的数组,开始从零开始记。当前结果总和超过结果值时,更新结果。
整体最优:最大的子数组的和。
因为需要考虑结果全部为负数的情况,因此将初始值设为int最小值。

实现

点击查看代码
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int result = INT32_MIN;
        int count = 0;
        for(int i = 0; i < nums.size(); i++) {
            count += nums[i];
            result = result > count ? result : count;
            if(count < 0) count = 0;
        }
        return result;
    }
};

复杂度分析

  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

标签:count,nums,int,复杂度,随想录,455,53,vector,result
From: https://www.cnblogs.com/suodi/p/16849404.html

相关文章