一、題目名稱java
Summary Ranges(獲取數組中數字的範圍)數組
二、題目地址code
https://leetcode.com/problems/summary-ranges/排序
三、題目內容leetcode
英文:Given a sorted integer array without duplicates, return the summary of its ranges.開發
中文:給出一個整數數組,返回這個數組中數字的範圍get
例如:給出數組 [0,1,2,4,5,7],返回 ["0->2","4->5","7"]it
四、解題方法io
本題的解題方法分爲如下兩步:class
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