228. Summary Ranges

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

因为是排序好的数组,所以只需每次向前扫描查找下一个数即可。

public class Solution {
  public List<String> summaryRanges(int[] nums) {
    List<String> result = new ArrayList<>();
    for (int i = 0; i < nums.length; i++) {
      int j = 0;
      while (i + j + 1 < nums.length && nums[i + j] == nums[i + j + 1] - 1) {
        j++;
      }
      if (j == 0) {
        result.add("" + nums[i]);
      } else {
        result.add(nums[i] + "->" + nums[i + j]);
      }
      i += j;
    }
    return result;
  }
}

posted on 2015-06-27 08:53  shini  阅读(124)  评论(0编辑  收藏  举报

导航