力扣打卡day07——最大子数组和、合并区间

53. 最大子数组和 - 力扣(LeetCode)

复制代码
class Solution {
    public int maxSubArray(int[] nums) {
        //这个题就是直接通过for进行判断,每次相加找出最大值
        int n=nums.length;
        int count=0;
        int result=Integer.MIN_VALUE;
    
        for(int i=0;i<n;i++){
            count+=nums[i];
            result=Math.max(result,count);
            //相加的时候小于0就进行重置
            if(count<0){
                count=0;
            }
        }
        return result;
    }
}

56. 合并区间 - 力扣(LeetCode)

思路:

先按首位置进行排序;

接下来,如何判断两个区间是否重叠呢?比如 a = 1,4,b = 2,3

当 a1 >= b0 说明两个区间有重叠.

但是如何把这个区间找出来呢?

左边位置一定是确定,就是 a0,而右边位置是 max(a1, b1)

所以,我们就能找出整个区间为:1,4

复制代码
class Solution {
    public int[][] merge(int[][] intervals) {
         List<int []> list=new ArrayList<>();

         //为空判断
         if(intervals ==null || intervals.length==0 ){
            return new int[0][];
         }
         if(intervals.length==1){
            return intervals;
         }
         //进行排序
         Arrays.sort(intervals,(a,b)-> a[0]-b[0]);
         int left,right;
         int i=0;
         //循环取数
         while(i<intervals.length){
            left=intervals[i][0];
            right=intervals[i][1];
            //判断两个区间是否重叠,如有就进行
            while(i<intervals.length-1 && right>=intervals[i+1][0]){
                right=Math.max(right,intervals[i+1][1]);
                i++;
            }
            list.add(new int[]{left,right});
           i++;
         }
         return list.toArray(new int[0][]);
    }
}
相关推荐
tryxr34 分钟前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_338 分钟前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Selvaggia1 小时前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法
Navigator_Z1 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.1 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.2 小时前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
wzdark2 小时前
数据压缩算法的时间复杂度与压缩率权衡4
算法
小陈phd2 小时前
深入理解agent学习笔记(一)——现代agent介绍
人工智能·算法
晴天的雨.9925 小时前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
aramae12 小时前
MySQL复合查询(8)
java·c语言·开发语言·后端·算法