码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 228 Summary Ranges

时间:2015-07-10 23:33:20      阅读:232      评论: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"].

解题思路:

JAVA实现如下:

public List<String> summaryRanges(int[] nums) {
        List<String> list = new ArrayList<String>();
		if (nums.length == 0)
			return list;
		int left = nums[0], index = nums[0];
		for (int i = 1; i < nums.length; i++) {
			if (index == nums[i] - 1)
				index++;
			else if (index == left) {
				list.add(index + "");
				left = nums[i];
				index = nums[i];
			} else {
				list.add(left + "->" + index);
				left = nums[i];
				index = nums[i];
			}

		}
		if (index == left) 
				list.add(index + "");
		else 
				list.add(left + "->" + index);
			
		return list;
    }

 

Java for LeetCode 228 Summary Ranges

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4637605.html

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