C++實現LeetCode(228.總結區間)

[LeetCode] 228.Summary Ranges 總結區間

Given a sorted integer array without duplicates, return the summary of its ranges.

Example 1:

Input:  [0,1,2,4,5,7]
Output: [“0->2″,”4->5″,”7”]
Explanation: 0,1,2 form a continuous range; 4,5 form a continuous range.

Example 2:

Input:  [0,2,3,4,6,8,9]
Output: [“0″,”2->4″,”6″,”8->9”]
Explanation: 2,3,4 form a continuous range; 8,9 form a continuous range.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

這道題給定我們一個有序數組,讓我們總結區間,具體來說就是讓我們找出連續的序列,然後首尾兩個數字之間用個“->”來連接,那麼我隻需遍歷一遍數組即可,每次檢查下一個數是不是遞增的,如果是,則繼續往下遍歷,如果不是瞭,我們還要判斷此時是一個數還是一個序列,一個數直接存入結果,序列的話要存入首尾數字和箭頭“->”。我們需要兩個變量i和j,其中i是連續序列起始數字的位置,j是連續數列的長度,當j為1時,說明隻有一個數字,若大於1,則是一個連續序列,代碼如下:

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> res;
        int i = 0, n = nums.size();
        while (i < n) {
            int j = 1;
            while (i + j < n && (long)nums[i + j] - nums[i] == j) ++j;
            res.push_back(j <= 1 ? to_string(nums[i]) : to_string(nums[i]) + "->" + to_string(nums[i + j - 1]));
            i += j;
        }
        return res;
    }
};

類似題目:

Missing Ranges

Data Stream as Disjoint Intervals 

參考資料:

https://leetcode.com/problems/summary-ranges/

https://leetcode.com/problems/summary-ranges/discuss/63451/9-lines-c%2B%2B-0ms-solution

https://leetcode.com/problems/summary-ranges/discuss/63219/Accepted-JAVA-solution-easy-to-understand

到此這篇關於C++實現LeetCode(228.總結區間)的文章就介紹到這瞭,更多相關C++實現總結區間內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: