LeetCode: Summary Ranges Solution
Straight forward checkingApproach
On each iteration, init
start
and end
to be equal to the iterated elementKeep assigning
end
while next element is greater than the current by one unitIf
start !== end
then it's a sub rangeImplementation
1var summaryRanges = function (nums) {2 let start, end3 let res = []45 for (let i = 0; i < nums.length; i++) {6 start = end = nums[i]78 for (; nums[i + 1] === nums[i] + 1; i++) {9 end = nums[i + 1]10 }1112 res.push(start === end ? "" + start : start + "->" + end)13 }1415 return res16}
Comments
Loading comments...
Tags
leetcode
array
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.