码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode Summary Ranges

时间:2015-10-11 08:59:16      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

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


解题思路:

直观思路,判断nums[i]- nums[i-1]是否为1,是就继续,不是就判定范围,存入ArrayList.


Java code:

public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> result = new ArrayList<String>();
        if(nums == null || nums.length == 0){
            return result;
        }
        int left = nums[0];
        int right = 0;
        for(int i = 1; i < nums.length; i++){
            if(nums[i] - nums[i-1] != 1){
                right = nums[i-1];
                if(left == right){
                    result.add("" + left);
                }else {
                    result.add(left + "->"+right);
                }
                left = nums[i];
            }
        }
        right = nums[nums.length-1];
        if(left == right){
            result.add("" + left);
        }else {
            result.add(left + "->"+right);
        }
        return result;
    }
}

 

Leetcode Summary Ranges

标签:

原文地址:http://www.cnblogs.com/anne-vista/p/4868765.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!