[LeetCode]8. Summary Ranges統計範圍

來源:互聯網
上載者:User

標籤:

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

For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].

 

解法:(1)初始化兩個遊標ind1=0,ind2=1,一個左邊界left=ind1;(2)若nums[ind2]-nums[ind1]==1則ind1++、ind2++,否則可以得到一個範圍[nums[left], nums[ind2-1]],將其存入結果中,同時更新遊標ind1=ind2,且ind2++,更新左邊界left=ind1;(3)若ind2<nums.size(),則跳轉到(2),否則處理最後剩下的一個範圍。

class Solution2 {public:    vector<string> summaryRanges(vector<int>& nums) {        int n = nums.size();        if (n == 0)            return vector<string>();        if (n == 1)            return vector<string>(1, intToString(nums[0]));        int ind1 = 0;        int ind2 = 1;        int left = ind1;        vector<string> res;        while (ind1 < n && ind2 < n)        {            if (nums[ind2] == nums[ind1] + 1)            {                ind2++;                ind1++;            }            else            {                string rs = "";                rs += intToString(nums[left]);                if (ind2 - 1 != left)                    rs += "->" + intToString(nums[ind2 - 1]);                left = ind1 = ind2++;                res.push_back(rs);            }        }        string rs = "";        rs += intToString(nums[left]);        if (--ind2 != left)            rs += "->" + intToString(nums[ind2]);        res.push_back(rs);        return res;    }private:    string intToString(const int& i)    {                stringstream ss;        ss << i;        string s = ss.str();        return s;    }};

 注意:(1)考慮nums.size()為0或者1的情況;(2)整數轉換為string的處理,考慮負數、最小的整數和最大的整數這些極端情況。可以使用to_string()。

[LeetCode]8. Summary Ranges統計範圍

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.