[LeetCode Algorithm Series Problem Solutions] Questions 56~60

LeetCode 56. Merging intervals (medium)

[Title description]

Use an array intervalsto represent a set of several intervals, where a single interval is intervals[i] = [start_i, end_i]. Please merge all overlapping intervals and return an array of non-overlapping intervals that exactly covers all intervals in the input .

【Example 1】

输入:intervals = [[1,3],[2,6],[8,10],[15,18]]
输出:[[1,6],[8,10],[15,18]]
解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].

【Example 2】

输入:intervals = [[1,4],[4,5]]
输出:[[1,5]]
解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。

【hint】

1 ≤ intervals . length ≤ 1 0 4 1\le intervals.length\le 10^41intervals.length104
i n t e r v a l s [ i ] . l e n g t h = = 2 intervals[i].length == 2 intervals[i].length==2
0 ≤ start ≤ end ≤ 1 0 4 0\le start_i\le end_i\le 10^40startiendi104

【analyze】


The interval merging template question is a greedy problem. First, sort all intervals by their left endpoints, then traverse each interval, and record the left and right endpoints l, rl, r of each new interval.l,r , if the current intervaliiThe left endpoint of i is not in [l, r] [l,r][l,r ] , indicating that there is no way to merge,[ l , r ] [l,r][l,r ] is a new interval, record it, and thenl, rl, rl,r is updated to the left and right endpoints of the current interval; if the current intervaliiThe left endpoint of i is at [ l , r ] [l,r][l,r ] , then the right endpoint of the new interval may be updated, that isr = max(r, intervals[i][1]).


【Code】

class Solution {
    
    
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals) {
    
    
        vector<vector<int>> res;
        sort(intervals.begin(), intervals.end());
        int l = intervals[0][0], r = intervals[0][1];
        for (int i = 1; i < intervals.size(); i++)
            if (intervals[i][0] > r)
            {
    
    
                res.push_back({
    
     l, r });
                l = intervals[i][0], r = intervals[i][1];
            }
            else r = max(r, intervals[i][1]);
        res.push_back({
    
     l, r });  // 注意别忘了最后一段
        return res;
    }
};

LeetCode 57. Insert interval (medium)

[Title description]

Give you a non-overlapping list of intervals sorted by the start and endpoints of the intervals.
When inserting a new range into a list, you need to make sure that the ranges in the list are still ordered and do not overlap (merging ranges 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]]

【hint】

1 ≤ intervals . length ≤ 1 0 4 1\le intervals.length\le 10^41intervals.length104
i n t e r v a l s [ i ] . l e n g t h = = 2 intervals[i].length == 2 intervals[i].length==2
0 ≤ i n t e r v a l s [ i ] [ 0 ] ≤ i n t e r v a l s [ i ] [ 1 ] ≤ 1 0 5 0\le intervals[i][0]\le intervals[i][1]\le 10^5 0intervals[i][0]intervals[i][1]105
intervals According tointervals[i][0]Sortascending order
new Interval .length == 2 newInterval.length == 2newInterval.length==2
0 ≤ new I nterval [ 0 ] ≤ new I nterval [ 1 ] ≤ 1 0 5 0\le newInterval[0]\le newInterval[1]\le 10^50newInterval[0]newInterval[1]105

【analyze】


If intervals[i][1] < newInterval[0], it means that the interval is completely on newIntervalthe left side of , and there is no intersection; if intervals[i][1] >= newInterval[0] && intervals[i][0] <= newInterval[1], it means that there is an overlapping part, and the operation of merging the intervals needs to be performed; if intervals[i][0] > newInterval[1], it means that the interval is completely on newIntervalthe right side of, there is no intersection.


【Code】

class Solution {
    
    
public:
    vector<vector<int>> insert(vector<vector<int>>& a, vector<int>& b) {
    
    
        vector<vector<int>> res;
        int k = 0;
        while (k < a.size() && a[k][1] < b[0]) res.push_back(a[k++]);
        while (k < a.size() && a[k][1] >= b[0] && a[k][0] <= b[1])
            b[0] = min(b[0], a[k][0]), b[1] = max(b[1], a[k][1]), k++;
        res.push_back(b);
        while (k < a.size()) res.push_back(a[k++]);
        return res;
    }
};

LeetCode 58. Length of last word (simple)

[Title description]

You are given a string sconsisting of several words separated by some space characters before and after the words. Returns the length of the last word in a string.
A word is the largest substring that consists only of letters and does not contain any space characters.

【Example 1】

输入:s = "Hello World"
输出:5
解释:最后一个单词是“World”,长度为5。

【Example 2】

输入:s = "   fly me   to   the moon  "
输出:4
解释:最后一个单词是“moon”,长度为4。

【Example 3】

输入:s = "luffy is still joyboy"
输出:6
解释:最后一个单词是长度为6的“joyboy”。

【hint】

1 ≤ s length ≤ 1 0 4 1\and s.length\and 10^41s.length104Only
s English letters and spaces' 'form
sat least one word in

【analyze】


There are many ways to approach this question. You can use Python's splitfunction to filter out spaces; you can also use C++ to stringstreamcontinuously read strings, and the reading process will automatically filter out spaces; you can also use double pointers to traverse from back to front to find the first string. word.


【Code】

【Python code】

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        return len(s.split()[-1])

[C++ StringStream code]

class Solution {
    
    
public:
    int lengthOfLastWord(string s) {
    
    
        stringstream ssin(s);
        string res;
        while (ssin >> res);
        return res.size();
    }
};

[Manual implementation]

class Solution {
    
    
public:
    int lengthOfLastWord(string s) {
    
    
        int i = s.size() - 1;
        while (i >= 0 && s[i] == ' ') i--;
        int j = i - 1;
        while (j >= 0 && s[j] != ' ') j--;
        return i - j;
    }
};

LeetCode 59. Spiral Matrix II (Medium)

[Title description]

Given a positive integer n, generate a value containing 1 11 ton 2 n^2n2 all elements, and the elements are spirally arranged in clockwisen x nordermatrix.

【Example 1】

Insert image description here

输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

【Example 2】

输入:n = 1
输出:[[1]]

【hint】

1 ≤ n ≤ 20 1\le n\le 201n20

【analyze】


Like question 54 , just define the four direction vectors and simulate filling in each number.


【Code】

class Solution {
    
    
public:
    vector<vector<int>> generateMatrix(int n) {
    
    
        vector<vector<int>> res(n, vector<int>(n));
        int dx[] = {
    
     0, 1, 0, -1 }, dy[] = {
    
     1, 0, -1, 0 };
        for (int i = 1, x = 0, y = 0, d = 0; i <= n * n; i++)
        {
    
    
            res[x][y] = i;
            int nx = x + dx[d], ny = y + dy[d];
            if (nx < 0 || nx >= n || ny < 0 || ny >= n || res[nx][ny]) d = (d + 1) % 4;
            x += dx[d], y += dy[d];
        }
        return res;
    }
};

LeetCode 60. kth permutation (difficult)

[Title description]

Given a set [1,2,3,...,n], all its elements have n!permutations.

List all arrangements in order of size and label them one by one. At that n = 3time , all arrangements are as follows:

  • "123"
  • "132"
  • "213"
  • "231"
  • "312"
  • "321"

Given nand k, return the th kpermutation.

【Example 1】

输入:n = 3, k = 3
输出:"213"

【Example 2】

输入:n = 4, k = 9
输出:"2314"

【Example 3】

输入:n = 3, k = 1
输出:"123"

【hint】

1 ≤ n ≤ 9 1\le n\le 91n9
1 ≤ k ≤ n! 1\the k\the n!1kn!

【analyze】


We can enumerate the number filled in each position, taking as n = 4, k = 10an example :

  • First enumerate what number the first one should be. If it is 1, then there are a total of combinations of the next three positions 3!, that is, when the first number is , 1the resulting arrangement is 1 ∼ 6 1\sim 616 , then the answer must not be here, willk - 3! = 4; then the first number of the enumeration is not2, at this time3! >= 4, so the first number of the answer is2.
  • Enumerate the second number, if it is 1, then 2! < 4, then k - 2! = 2; if it is 3, then 2! >= 2, so the second number of the answer is 3.
  • Enumerate the third number, if it is 1, then 1! < 2, then k - 1! = 1; if it is 4, then 1! >= 1, so the third number of the answer is 4.
  • Enumerate the fourth number. At this time, only 1has not been used, and 0! >= 1, so the fourth number of the answer is 1.

【Code】

class Solution {
    
    
public:
    string getPermutation(int n, int k) {
    
    
        string res;
        vector<bool> st(10);  // 记录每个数是否被用过
        for (int i = 0; i < n; i++)  // 一共要填入n个数
        {
    
    
            int fact = 1;  // 阶乘,当填到第i个数时,后面还有n-i-1个数可以自由排列
            for (int j = 1; j <= n - i - 1; j++) fact *= j;
            for (int j = 1; j <= n; j++)
                if (!st[j])
                {
    
    
                    if (fact < k) k -= fact;
                    else
                    {
    
    
                        res.push_back(j + '0');
                        st[j] = true;
                        break;
                    }
                }
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/m0_51755720/article/details/132671522