标签:
1、题目名称
Summary Ranges(获取数组中数字的范围)
2、题目地址
https://leetcode.com/problems/summary-ranges/
3、题目内容
英文:Given a sorted integer array without duplicates, return the summary of its ranges.
中文:给出一个整数数组,返回这个数组中数字的范围
例如:给出数组 [0,1,2,4,5,7],返回 ["0->2","4->5","7"]
4、解题方法
本题的解题方法大致分为以下两步:
1)对数组进行排序
2)从前向后遍历数组,计算区间,并将每个区间放入一个List中
计算完毕后,返回List
Java代码如下:
import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @功能说明:LeetCode 228 - Summary Ranges * @开发人员:Tsybius2014 * @开发时间:2015年10月11日 */ public class Solution { /** * 获取数组中数字的范围 * @param nums 数组 * @return */ public List<String> summaryRanges(int[] nums) { Arrays.sort(nums); List<String> list = new ArrayList<String>(); if (nums.length == 0) { return list; } int begin = Integer.MIN_VALUE; int end = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++) { if (i == 0) { begin = nums[i]; } else if (nums[i - 1] < nums[i] - 1) { list.add(getInterval(begin, end)); begin = nums[i]; } end = nums[i]; if (i == nums.length - 1) { list.add(getInterval(begin, end)); } } return list; } /** * 获取两个数字包含的范围 * @param begin 起始数字 * @param end 终止数字 * @return */ private String getInterval(int begin, int end) { String result = ""; if (begin == end) { result = String.valueOf(begin); } else if (begin < end) { result = String.valueOf(begin) + "->" + String.valueOf(end); } return result; } }
END
LeetCode:Summary Ranges - 获取数组中数字的范围
标签:
原文地址:http://my.oschina.net/Tsybius2014/blog/515470