[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
时间: 2024-09-30 12:51:10

[LeetCode] Summary Ranges的相关文章

[LeetCode]228.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"]. 代码 /*--------------------------------------- * 日期:2015-08-04 * 作者:SJF01

LeetCode All in One 题目讲解汇总(持续更新中...)

终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 如果各位看官们,大神们发现了任何错误,或是代码无法通过OJ,或是有更好的解法,或是有任何疑问,意见和建议的话,请一定要在对应的帖子下面评论区留言告知博主啊,多谢多谢,祝大家刷得愉快,刷得精彩,刷出美好未来- 博主制作了一款iOS的应用"Leetcode Meet Me",里面有Leetcode上所有的题目,并且贴上了博主的解法,随时随地都能

[LeetCode] Maximum Average Subarray II 子数组的最大平均值之二

Given an array consisting of n integers, find the contiguous subarray whose length is greater than or equal to k that has the maximum average value. And you need to output the maximum average value. Example 1: Input: [1,12,-5,-6,50,3], k = 4 Output:

[LeetCode] Design Log Storage System 设计日志存储系统

You are given several logs that each log contains a unique id and timestamp. Timestamp is a string that has the following format: Year:Month:Day:Hour:Minute:Second, for example, 2017:01:01:23:59:59. All domains are zero-padded decimal numbers. Design

代码分析-leetcode:Scramble String问题

问题描述 leetcode:Scramble String问题 题目:Given a string s1 we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. Below is one possible representation of s1 = ""great"": great / gr eat / / g r e at /

c++-leetcode Median of Two Sorted Arrays

问题描述 leetcode Median of Two Sorted Arrays class Solution { public: double findMedianSortedArrays(vector& nums1, vector& nums2) { if(nums1.size()==0){ if(nums2.size()%2==0)return ((double)nums2[nums2.size()/2]+nums2[nums2.size()/2-1])/2.0; else ret

[LeetCode]61.Rotate List

[题目] Given a list, rotate the list to the right by k places, where k is non-negative. For example: Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL. [题意] 给定一个链表,向右旋转k个位置,其中k是非负的. [分析] 先遍历一遍,得出链表长度 len,注意 k 可能大于

[LeetCode]91.Decode Ways

题目 A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 - 'Z' -> 26 Given an encoded message containing digits, determine the total number of ways to decode it. For example, Given encode

HTML5教程:如何使用details元素和summary元素

文章简介:details 和 summary 元素. 曾几何时,我们创建可以显示/隐藏一些内容的小组件时,我们不得不使用Javascript.有时候你可能不得不为这个小功能,下载一个完整的 JS 库才能达到这个功能效果.为下面的时刻欢呼吧!HTML5提供了创建这种拖拽特点的方法,我们仅仅需要简单的几行html代码就能获得这种效果(从目前而言,这种效果还依赖于使用的浏览器,当然,在不久的将来,这可能不是问题).下面让我们一起来看看 <detail>元素. 下面就是规范中的描述 The detai