Created
November 7, 2017 18:26
-
-
Save hoanbka/fffe32393ae7bead7c7b51249479d837 to your computer and use it in GitHub Desktop.
Summary Ranges
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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