Skip to content

Instantly share code, notes, and snippets.

@hoanbka
Created November 7, 2017 18:26
Show Gist options
  • Save hoanbka/fffe32393ae7bead7c7b51249479d837 to your computer and use it in GitHub Desktop.
Save hoanbka/fffe32393ae7bead7c7b51249479d837 to your computer and use it in GitHub Desktop.
Summary Ranges
/**
* Created by Hoan Nguyen on 11/8/2017.
* https://leetcode.com/problems/summary-ranges/description/
*
*/
/**
* @param {number[]} nums
* @return {string[]}
*/
var summaryRanges = function(nums) {
var output = [];
var temp = "";
for (var i = 0; i < nums.length; i++) {
if (!temp) {
temp += nums[i];
if (nums[i] + 1 !== nums[i + 1]) {
output.push(temp);
temp = "";
}
}
else {
if (nums[i] + 1 !== nums[i + 1]) {
temp += "->";
temp += nums[i];
output.push(temp);
temp = "";
}
}
}
if (temp) output.push(temp);
return output;
};
console.log(summaryRanges([0, 1, 2, 4, 5, 7]));
console.log(summaryRanges([0, 2, 3, 4, 6, 8, 9]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment