[LeetCode] Summary Ranges,leetcoderanges

來源:互聯網
上載者:User

[LeetCode] Summary Ranges,leetcoderanges

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"].

解題思路

略

實現代碼

C++:

// Runtime: 0 msclass Solution {public:    vector<string> summaryRanges(vector<int>& nums) {        vector<string> results;        int start = 0;        for (int i = 1; i <= nums.size(); i++)        {            if (i == nums.size() || nums[i - 1] + 1 < nums[i])            {                string temp = num2str(nums[start]);                if (start + 1 < i)                {                    temp += "->";                    temp += num2str(nums[i - 1]);                }                results.push_back(temp);                start = i;            }        }        return results;    }    string num2str(long long n)    {        if (n == 0)        {            return "0";        }        string temp = "";        bool flag = false;        if (n < 0)        {            flag = true;            n = -n;        }        while (n)        {            temp = (char)(n % 10 + '0') + temp;            n /= 10;        }        if(flag)        {            temp = '-' + temp;        }        return temp;    }};

Java:

// Runtime: 268 mspublic class Solution {    public List<String> summaryRanges(int[] nums) {        List<String> res = new ArrayList<String>();        int begin = 0;        for (int i = 1; i <= nums.length; i++){            if (i == nums.length || nums[i] > nums[i-1] + 1){                StringBuilder sb = new StringBuilder();                sb.append(nums[begin]);                if (i > begin + 1){                    sb.append("->");                    sb.append(nums[i-1]);                }                res.add(sb.toString());                begin = i;            }        }        return res;    }}

Python:

# Runtime: 36 msclass Solution:    # @param {integer[]} nums    # @return {string[]}    def summaryRanges(self, nums):        x, size = 0, len(nums)        ans = []        while x < size:            c, r = x, str(nums[x])            while (x + 1) < size and nums[x+1] == nums[x] + 1:                x += 1            if x > c:                r += '->' + str(nums[x])            ans.append(r)            x += 1        return ans

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.