溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

LeetCode怎么插入?yún)^(qū)間

發(fā)布時(shí)間:2021-12-15 14:54:59 來(lái)源:億速云 閱讀:149 作者:小新 欄目:大數(shù)據(jù)

小編給大家分享一下LeetCode怎么插入?yún)^(qū)間,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

1,問(wèn)題簡(jiǎn)述

    給出一個(gè)無(wú)重疊的 ,按照區(qū)間起始端點(diǎn)排序的區(qū)間列表。在列表中插入一個(gè)新的區(qū)間,你需要確保列表中的區(qū)間仍然有序且不重疊(如果有必要的話,可以合并區(qū)間)。

2,示例

示例 1:
輸入:intervals = [[1,3],[6,9]], newInterval = [2,5]輸出:[[1,5],[6,9]]示例 2:
輸入:intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]輸出:[[1,2],[3,10],[12,16]]解釋:這是因?yàn)樾碌膮^(qū)間 [4,8] 與 [3,5],[6,7],[8,10] 重疊。 
注意:輸入類型已在 2019 年 4 月 15 日更改。請(qǐng)重置為默認(rèn)代碼定義以獲取新的方法簽名。

3,題解思路

     其實(shí)這道題和前面的合并區(qū)間那道題的整個(gè)題解思路是一樣的,將新數(shù)組元素裝入到集合里面,然后將集合元素排序一下,然后進(jìn)行邏輯判斷,這里使用了集合作為一個(gè)臨時(shí)存儲(chǔ)空間,比較相鄰區(qū)間的內(nèi)容,如前一個(gè)區(qū)間右端點(diǎn)的值和下一個(gè)區(qū)間左端點(diǎn)的值做比較,符合合并的時(shí)候進(jìn)行合并之后放入結(jié)果集,不符合合并的也放入結(jié)果集中,當(dāng)所有的區(qū)間都處理完成之后,符合合并的數(shù)據(jù)就處理完成了,這也是本題的主要思路

4,題解程序


import java.util.*;
public class InsertTest {    public static void main(String[] args) {        int[][] intervals = {                {1, 3},                {6, 9}        };
       int[] newInterval = {2, 5};

       int[][] insert = insert(intervals, newInterval);        for (int[] arr : insert) {            System.out.println(arr[0] + "    " + arr[1]);        }    }
   public static int[][] insert(int[][] intervals, int[] newInterval) {        if ((intervals == null) && newInterval == null) {            return new int[][]{newInterval};        }
       List<int[]> list = new ArrayList<>();        Collections.addAll(list, intervals);        list.add(newInterval);        int[][] tempArray = list.toArray(new int[0][]);        List<int[]> result = new ArrayList<>();        Arrays.sort(tempArray, Comparator.comparingInt(x -> x[0]));        List<int[]> tempList = new ArrayList<>();        Collections.addAll(tempList, tempArray);        int[] temp = tempList.get(0);        for (int i = 1; i < tempList.size(); i++) {            if (tempList.get(i)[0] <= temp[1]) {                temp = new int[]{temp[0], Math.max(temp[1], tempList.get(i)[1])};            } else {                result.add(temp);                temp = tempList.get(i);            }        }        result.add(temp);        int[][] array = result.toArray(new int[0][]);        return array;    }}

5,題解程序圖片版

LeetCode怎么插入?yún)^(qū)間

以上是“LeetCode怎么插入?yún)^(qū)間”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI