Summary Ranges 解答

Question

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

Solution

Traverse array, remember not to forget the last element.

 1 public class Solution {
 2     public List<String> summaryRanges(int[] nums) {
 3         int length = nums.length;
 4         List<String> result = new ArrayList<String>();
 5         if (length == 0)
 6             return result;
 7         StringBuffer tmp = new StringBuffer();
 8         int startNum = nums[0];
 9         int endNum = nums[0];
10         if (length == 1) {
11             tmp.append(startNum);
12             result.add(tmp.toString());
13             return result;
14         }
15         for (int i = 0; i < length - 1; i++) {
16             if (nums[i] != nums[i + 1] - 1) {
17                 tmp = new StringBuffer();
18                 endNum = nums[i];
19                 if (startNum == endNum) {
20                     tmp.append(startNum);
21                 } else {
22                     tmp.append(startNum);
23                     tmp.append("->");
24                     tmp.append(endNum);
25                 }
26                 result.add(tmp.toString());
27                 startNum = nums[i + 1];
28             }
29         }
30         tmp = new StringBuffer();
31         endNum = nums[length - 1];
32         if (startNum == endNum) {
33             tmp.append(startNum);
34         } else {
35             tmp.append(startNum);
36             tmp.append("->");
37             tmp.append(endNum);
38         }
39         result.add(tmp.toString());
40         return result;
41     }
42 }
posted @ 2015-09-11 07:56  树獭君  阅读(149)  评论(0编辑  收藏  举报