首页 > 其他分享 >2023-06-03 刷题

2023-06-03 刷题

时间:2023-06-03 09:13:11浏览次数:45  
标签:03 newInterval 06 cur int intervals answer end 刷题

练习英文描述算法

56. 合并区间 - 力扣(LeetCode) [mid, 非常好展示思路]

分析:

  • First sort the intervals by start time, so that we can easily find which intervals can be merged by checking intervals from left to right.
  • Use one example to demo the process. (e.g. use java comment, to show the merging process.).
class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        
        List<int[]> answer = new ArrayList<>();
        for (int[] interval: intervals) {
            int start = interval[0], end = interval[1];
            if (answer.isEmpty() || answer.get(answer.size() - 1)[1] < start) { // no overlap
                answer.add(interval);
            } else {
                int[] last = answer.get(answer.size() - 1);
                last[1] = Math.max(last[1], end);
            }
        }
        return answer.toArray(new int[answer.size()][2]); // keep in mind
    }
}
/*
    [[1,3],[2,6],[8,10],[15,18]]
cur:                              |


answer: [[1,6], [8, 10], [15, 18]]
    has overlap:  last.end >= cur.start, update last.end
       last.end = max(last.end, cur.end)
    no overlap:  add it to answer
*/

57. 插入区间 - 力扣(LeetCode) 【mid,非常容易困惑】

// 一种比较优雅的写法
class Solution {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> answer = new ArrayList<>();
        for (int[] cur : intervals) {
            if (newInterval == null || cur[1] < newInterval[0]) { // left part
                answer.add(cur);
            } else if (newInterval[1] < cur[0]) { // right part, first one
                answer.add(newInterval);
                answer.add(cur);
                newInterval = null;
            } else { // middle overlap
                newInterval[0] = Math.min(newInterval[0], cur[0]);
                newInterval[1] = Math.max(newInterval[1], cur[1]);
            }
        }
        if (newInterval != null) {  // newInterval very long
            answer.add(newInterval);
        }
        return answer.toArray(new int[answer.size()][2]);
    }
}
/*
     [[1,2],   [3,5],[6,7],[8,10],   [12,16]]
cur:   left       middle               right
     cur[1] < start
                 start <= cur[1] &&
                 end >= cur[0]
                                      cur[0] > end

newInterval = [3,8]  (start, end) 

coding skill detail:
    handle the middle part is complex, the condition is complex.
    so why not handle left, right first, then the remaining is the middle.
        left part is easy to coding.
        how to know right part starts?  checking first one in the right part, then
            mark interval as null, so that we can add it directly.
        otherwise, merge newInterval with current one

In summary, we handle three cases in the loop body: 
	add left, part of right part
	add first of right part (& newInterval)
	merge middle
after loop, need to consider, newInterval is not added if it is too long.
*/

另外一种写法,就是分成三段,用下标,这种写法也更清楚一点吧,虽然长一点,但是性能更好:

class Solution {
    public int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> ans = new ArrayList<>();
        int i = 0, n = intervals.length;
        int start = newInterval[0], end = newInterval[1];
        for (; i < n && intervals[i][1] < start; i++) { // left part
            ans.add(intervals[i]);
        }
        // middle, handle overlap
        for(; i < n && intervals[i][0] <= end; i++) {
            start = Math.min(start, intervals[i][0]);
            end = Math.max(end, intervals[i][1]);
        }
        ans.add(new int[] {start, end});
        
        for(; i < n; i++) { // right part
            ans.add(intervals[i]);
        }

        return ans.toArray(new int[ans.size()][2]);
    }
}
/*
     [[1,2],   [3,5],[6,7],[8,10],   [12,16]]
cur:   left       middle               right
     cur[1] < start
                 start <= cur[1] &&
                 end >= cur[0]
                                      cur[0] > end

newInterval = [3,8]  (start, end) 
*/

1272. 删除区间 - 力扣(LeetCode) [mid, 细节太多了]

分析:

  • 看到一个非常好的写法,借鉴一下。这个跟57的insertInterval有一点不同。可以直接处理左右不相交的部分。对于overlap的部分,考虑最后还剩下哪些比较好。画图能清晰说明这个问题。比自己在纸上写要快很多,而且直观。
class Solution {
    public List<List<Integer>> removeInterval(int[][] intervals, int[] toBeRemoved) {
        List<List<Integer>> ans = new ArrayList<>();
        for (int[] cur : intervals) {
            // left no overlap & right no overlap
            if (cur[1] < toBeRemoved[0] || cur[0] > toBeRemoved[1]) {
                ans.add(Arrays.asList(cur[0], cur[1]));
            } else { // has overlap
                if (cur[0] < toBeRemoved[0]) {
                    ans.add(Arrays.asList(cur[0], toBeRemoved[0]));
                }
                if (cur[1] > toBeRemoved[1]) { 
                    ans.add(Arrays.asList(toBeRemoved[1], cur[1]));
                }
            }
        }

        return ans;
    }
}

/*
   [[-5,-1],   [0,2],[3,4],[5,7],   [9,12]],   [1,6] --> (start, end)
cur                                   |
  left: cur.end < start
                   overlap (handle it): part of it overlap, includeded (may be multiple)
                                 right: cur.start > end
---  ---- --- ----  ------
        =========

--------
  ===

------
==

-----
  ===
*/

要考虑:区间端点相等的情况。这题如果直接思考overlap的几个部分,会很困难。

参考资料:

标签:03,newInterval,06,cur,int,intervals,answer,end,刷题
From: https://www.cnblogs.com/xianzhon/p/17453279.html

相关文章

  • 2023年06月在线IDE流行度最新排名
    点击查看最新在线IDE流行度最新排名(每月更新)2023年06月在线IDE流行度最新排名TOP在线IDE排名是通过分析在线ide名称在谷歌上被搜索的频率而创建的在线IDE被搜索的次数越多,人们就会认为它越受欢迎。原始数据来自谷歌Trends如果您相信集体智慧,那么TOPODE索引可以帮助您决定在......
  • 2023年06月数据库流行度最新排名
    点击查看最新数据库流行度最新排名(每月更新)2023年06月数据库流行度最新排名TOPDB顶级数据库索引是通过分析在谷歌上搜索数据库名称的频率来创建的一个数据库被搜索的次数越多,这个数据库就被认为越受欢迎。这是一个领先指标。原始数据来自谷歌Trends如果您相信集体智慧,那么TOP......
  • 03web安全学习---前端基础
    一、前端是什么?二、HTML最简单的架构三、JS的妙用......
  • 2023-06-02 用户访问cgi-bin/test-cgi时会泄露远端服务器名
    问题描述:百度智能云给我发了一条短信,说是我的服务器有个cgi安全漏洞:用户访问cgi-bin/test-cgi时会泄露远端服务器名,服务器地址等敏感信息,黑客可以利用获得的敏感信息执行下一步的攻击操作。我以前部署阿里云怎么就没这个问题?难道是宝塔的问题??现在我的服务器是用宝塔管理的,至......
  • 2023-06-02 练习算法 - TODO
    练习扫描线算法视频:基础算法(一)--扫描线_哔哩哔哩_bilibili391·NumberofAirplanesintheSky-LintCode【基础】“这个是扫描线的基础题,后面其他题目都是它的套娃。”253.会议室II-力扣(LeetCode)【MID】思路1:扫描线算法,很简单。复杂度分析:O(nlogn),空间:O(n)......
  • 2023-06-02:给定一个二进制数组 nums 和一个整数 k, k位翻转 就是从 nums 中选择一个长
    2023-06-02:给定一个二进制数组nums和一个整数k,k位翻转就是从nums中选择一个长度为k的子数组,同时把子数组中的每一个0都改成1,把子数组中的每一个1都改成0。返回数组中不存在0所需的最小k位翻转次数。如果不可能,则返回-1。子数组是数组的连续部分。输入:nums......
  • 总结20230602
    代码时间(包括上课)2h代码量(行):50行博客数量(篇):1篇相关事项:1、今天上午上的是计算机网络,实验报告的进度微乎其微。2、今天上午的第二节课是概率论,老师带着我们把知识点串了一遍,带着讲了讲卷子。3、今天下午是web考试,考的还可以,还有时间检查了一遍。......
  • bzoj1001 [BeiJing2006]狼抓兔子(网络流dinic算法||最短路spfa)
    http://www.lydsy.com/JudgeOnline/problem.php?id=10011001:[BeiJing2006]狼抓兔子TimeLimit: 15Sec  MemoryLimit: 162MBSubmit: 24017  Solved: 6068[Submit][Status][Discuss]Description现在小朋友们最喜欢的"喜羊羊与灰太狼",话说灰太狼抓羊不到,但抓......
  • SSO2.0 12-20230602
                 ......
  • [AGC038E] Gachapon
    ProblemStatementSnukefoundarandomnumbergenerator.Itgeneratesanintegerbetween$0$and$N-1$(inclusive).Anintegersequence$A_0,A_1,\cdots,A_{N-1}$representstheprobabilitythateachoftheseintegersisgenerated.Theinteger$i$($0......