228. Summary Ranges

栏目: Java · 发布时间: 5年前

内容简介:Given a sorted integer array without duplicates, return the summary of its ranges.Example 1:Example 2:

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.

难度:medium

题目:给定 排序 且无重复元素的整数数组,返回其连续元素的范围。

思路:用以变量记录连续元素的开始。

Runtime: 5 ms, faster than 7.57% of Java online submissions for Summary Ranges.

Memory Usage: 37.5 MB, less than 5.02% of Java online submissions for Summary Ranges.

class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> result = new ArrayList<>();
        if (null == nums || nums.length < 1) {
            return result;
        }
        
        for (int i = 1, start = 0; i <= nums.length; i++) {
            if (i == nums.length || nums[i] - nums[i - 1] != 1) {
                result.add((i - 1 == start) ? String.format("%s", nums[start]) 
                    : String.format("%s->%s", nums[start], nums[i - 1]));
                start = i;
            }
        }
        
        return result;
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

C++ How to Program (5th Edition) (How to Program)

C++ How to Program (5th Edition) (How to Program)

Harvey & Paul) Deitel & Associates / Prentice Hall / 2005-01-05 / USD 98.00

With over 250,000 sold, Harvey and Paul Deitel's C++ How to Program is the world's best-selling introduction to C++ programming. Now, this classic has been thoroughly updated! The Deitels' groundbreak......一起来看看 《C++ How to Program (5th Edition) (How to Program)》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具