Skip to content

Latest commit

 

History

History
77 lines (73 loc) · 2.1 KB

228.md

File metadata and controls

77 lines (73 loc) · 2.1 KB

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

给定一个已经排序并且无重复的数字数组,返回数组中数字的范围。 例如:给定[0,1,2,4,5,7],返回 ["0->2","4->5","7"]

这道题有意思,需要考虑的边缘比较多,比如空数组,只有一个元素的数组,左边独立、连续,右边独立、连续,第一次提交忽略了空数组,完败。:(

/**
 * @param {number[]} nums
 * @return {string[]}
 */
var summaryRanges = function(nums) {
  if (nums.length === 0) {
    return [];
  } else if (nums.length === 1) {
    return [nums[0].toString()];
  } else {
    var result = [];
    var first = 0;
    for (var i = 1; i < nums.length; i++ ) {
      if (nums[i-1] + 1 !== nums[i]) {
        if (first + 1 === i) {
          result.push(nums[first].toString());
        } else {
          result.push(nums[first] + '->' + nums[i-1]);
        }
        first = i;
      }
    }
    if (first + 1 === i) {
      result.push(nums[first].toString());
    } else {
      result.push(nums[first] + '->' + nums[i-1]);
    }
  }

  return result;
};
27 / 27 test cases passed.
Status: Accepted
Runtime: 148 ms

做完之后看discuss,看了几个Java版本的,果然还是能够改进的,我竟然忘记了用while来跳过连续的数字,用了while之后连最后一个元素都不用单独拿出来处理了。

/**
 * @param {number[]} nums
 * @return {string[]}
 */
var summaryRanges = function(nums) {
  if (nums.length === 1) {
    return [nums[0].toString()];
  } else {
    var result = [];
    for (var i = 0; i < nums.length; i++ ) {
      var first = nums[i];
      while(i + 1 < nums.length && nums[i+1] -nums[i] === 1) i++;
      if (first === nums[i]) {
        result.push(nums[i] + '');
      } else {
        result.push(first + '->' + nums[i]);
      }
    }
  }

  return result;
};
27 / 27 test cases passed.
Status: Accepted
Runtime: 140 ms

提高了8ms,还有大神用了128ms,以后再尝试优化吧。