LeetCode Summary Ranges(简单的数组处理)

来源:互联网 发布:wifi破解源代码 c语言 编辑:程序博客网 时间:2024/05/20 13:05

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、从起始位置开始遍历,直到后面的数与当前的数之差不等于1

           2、统计范围的起始和结束,从当前的结束位置的后一个数开始

          3、重复第1步

代码如下

public class Solution {    public List<String> summaryRanges(int[] nums)    {        List<String> res = new ArrayList<String>();        for (int i = 0, len = nums.length; i < len; i++) {            int j = i;            while (j + 1 < len && nums[j + 1] - nums[j] == 1) j++;            if (j < len) {                StringBuilder sb = new StringBuilder();                if (j - i > 0) {                    sb.append(nums[i] + "->" + nums[j]);                } else {                    sb.append(nums[i]);                }                res.add(sb.toString());            }            i = j;        }        return res;    }}

0 0
原创粉丝点击