楚兴

达则兼济天下,穷则独善其身。

[LeetCode] Summary Ranges

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 ms
class 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 ms
public 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 ms
class 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
阅读更多
版权声明:本文为博主原创或整理自网络,转载请注明出处。 https://blog.csdn.net/u011331383/article/details/46699047
文章标签: leetcode
个人分类: OJ
所属专栏: Enjoy LeetCode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

[LeetCode] Summary Ranges

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭