Algorithm leetcode|57. Insert interval (rust punches hard)



57. Interpolate range:

Gives you a non- overlapping list of intervals sorted by their start and end points.

To insert a new interval into a list, you need to make sure that the intervals in the list are still ordered and not overlapping (merging intervals if necessary).

Example 1:

输入:
	
	intervals = [[1,3],[6,9]], newInterval = [2,5]
	
输出:
	
	[[1,5],[6,9]]

Example 2:

输入:
	
	intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
	
输出:
	
	[[1,2],[3,10],[12,16]]
	
解释:
	
	这是因为新的区间 [4,8] 与 [3,5],[6,7],[8,10] 重叠。

Example 3:

输入:
	
	intervals = [], newInterval = [5,7]
	
输出:
	
	[[5,7]]

Example 4:

输入:
	
	intervals = [[1,5]], newInterval = [2,3]
	
输出:
	
	[[1,5]]

Example 5:

输入:
	
	intervals = [[1,5]], newInterval = [2,7]
	
输出:
	
	[[1,7]]

hint:

  • 0 <= intervals.length <= 104
  • intervals[i].length == 2
  • 0 <= intervals[i][0] <= intervals[i][1] <= 105
  • intervals sorted in ascending order according to intervals[i][0]
  • newInterval.length == 2
  • 0 <= newInterval[0] <= newInterval[1] <= 105

analyze:

  • Facing this algorithm problem, the second master fell into deep thought.
  • Simulate according to the meaning of the question, traverse the interval list, and analyze the possible situation of the newly inserted interval.
  • The new interval may be in front of the traversal interval, so insert the new interval directly at this position.
  • The new interval may be behind the traversed interval, so continue to traverse the next interval.
  • Some are complicated because there is overlap, and the intervals need to be merged, and the minimum value is taken as the start value of the interval, and the maximum value is used as the end value of the interval.

answer:

rust:

impl Solution {
    
    
    pub fn insert(intervals: Vec<Vec<i32>>, new_interval: Vec<i32>) -> Vec<Vec<i32>> {
    
    
        let (mut left, mut right) = (new_interval[0], new_interval[1]);
        let mut placed = false;
        let mut ans = Vec::new();
        intervals.into_iter().for_each(|interval| {
    
    
            if interval[0] > right {
    
    
                // 在插入区间的右侧且无交集
                if !placed {
    
    
                    ans.push(vec![left, right]);
                    placed = true;
                }
                ans.push(interval);
            } else if interval[1] < left {
    
    
                // 在插入区间的左侧且无交集
                ans.push(interval);
            } else {
    
    
                // 与插入区间有交集,计算它们的并集
                left = left.min(interval[0]);
                right = right.max(interval[1]);
            }
        });
        if !placed {
    
    
            ans.push(vec![left, right]);
        }
        return ans;
    }
}

go:

func insert(intervals [][]int, newInterval []int) (ans [][]int) {
    
    
    left, right := newInterval[0], newInterval[1]
	placed := false
	for _, interval := range intervals {
    
    
		if interval[0] > right {
    
    
			// 在插入区间的右侧且无交集
			if !placed {
    
    
				ans = append(ans, []int{
    
    left, right})
				placed = true
			}
			ans = append(ans, interval)
		} else if interval[1] < left {
    
    
			// 在插入区间的左侧且无交集
			ans = append(ans, interval)
		} else {
    
    
			// 与插入区间有交集,计算它们的并集
			if interval[0] < left {
    
    
				left = interval[0]
			}
			if interval[1] > right {
    
    
				right = interval[1]
			}
		}
	}
	if !placed {
    
    
		ans = append(ans, []int{
    
    left, right})
	}
	return
}

c++:

class Solution {
    
    
public:
    vector<vector<int>> insert(vector<vector<int>>& intervals, vector<int>& newInterval) {
    
    
        int left = newInterval[0], right = newInterval[1];
        bool placed = false;
        vector<vector<int>> ans;
        for (const auto &interval: intervals) {
    
    
            if (interval[0] > right) {
    
    
                // 在插入区间的右侧且无交集
                if (!placed) {
    
    
                    ans.push_back({
    
    left, right});
                    placed = true;
                }
                ans.emplace_back(interval);
            } else if (interval[1] < left) {
    
    
                // 在插入区间的左侧且无交集
                ans.emplace_back(interval);
            } else {
    
    
                // 与插入区间有交集,计算它们的并集
                left = min(left, interval[0]);
                right = max(right, interval[1]);
            }
        }
        if (!placed) {
    
    
            ans.push_back({
    
    left, right});
        }
        return ans;
    }
};

python:

class Solution:
    def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
        left, right = newInterval
        placed = False
        ans = list()
        for lv, rv in intervals:
            if lv > right:
                # 在插入区间的右侧且无交集
                if not placed:
                    ans.append([left, right])
                    placed = True
                ans.append([lv, rv])
            elif rv < left:
                # 在插入区间的左侧且无交集
                ans.append([lv, rv])
            else:
                # 与插入区间有交集,计算它们的并集
                left = min(left, lv)
                right = max(right, rv)
        if not placed:
            ans.append([left, right])
        return ans


java:

class Solution {
    
    
    public int[][] insert(int[][] intervals, int[] newInterval) {
    
    
        int         left    = newInterval[0];
        int         right   = newInterval[1];
        boolean     placed  = false;
        List<int[]> ansList = new ArrayList<int[]>();
        for (int[] interval : intervals) {
    
    
            if (interval[0] > right) {
    
    
                // 在插入区间的右侧且无交集
                if (!placed) {
    
    
                    ansList.add(new int[]{
    
    left, right});
                    placed = true;
                }
                ansList.add(interval);
            } else if (interval[1] < left) {
    
    
                // 在插入区间的左侧且无交集
                ansList.add(interval);
            } else {
    
    
                // 与插入区间有交集,计算它们的并集
                left = Math.min(left, interval[0]);
                right = Math.max(right, interval[1]);
            }
        }
        if (!placed) {
    
    
            ansList.add(new int[]{
    
    left, right});
        }
        return ansList.toArray(new int[ansList.size()][2]);
    }
}

Thank you very much for reading this article~
Welcome to [Like][Favorite][Comment]~It
is not difficult to give up, but it must be cool to persevere~
I hope we all can make a little progress every day~
This article is written by the white hat of the second master : https://le -yi.blog.csdn.net/blog original~


Guess you like

Origin blog.csdn.net/leyi520/article/details/131184793