标签:
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 class Solution { private List<String> sR = new ArrayList<String>(); private StringBuilder sb = new StringBuilder(); private boolean flag = false; private int start, tmp; public List<String> summaryRanges(int[] nums) { if (nums.length == 0) { return sR; } for (int i = 0; i < nums.length; i++) { if (i == 0) { start = nums[i]; tmp = nums[i]; continue; } if (nums[i] - tmp == 1) { tmp = nums[i]; flag = true; continue; } else if (flag) { sb.delete(0, sb.length()); sb.append(start + "->" + tmp); sR.add(sb.toString()); flag = false; } else { sR.add(Integer.toString(tmp)); } start = nums[i]; tmp = nums[i]; } if (flag) { sb.delete(0, sb.length()); sb.append(start + "->" + nums[nums.length - 1]); sR.add(sb.toString()); } else { sR.add(Integer.toString(nums[nums.length - 1])); } return sR; } }
标签:
原文地址:http://www.cnblogs.com/lasclocker/p/4803255.html