January 4, 2024

Viiisit [LeetCode] - 228. Summary Ranges

#php#javascript#ruby

keep learning, keep coding!

Problem - Summary Ranges

You are given a sorted unique integer array nums.

A range [a,b] is the set of all integers from a to b (inclusive).

Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums is covered by exactly one of the ranges, and there is no integer x such that x is in one of the ranges but not in nums.

翻譯蒟蒻

給定一個已排序且獨特的整數陣列 nums,要找出最小的一組排序範圍列表,這些範圍要包含陣列中的所有數字。


Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* @param {number[]} nums
* @return {string[]}
*/
var summaryRanges = function(nums) {
let record = [];
for (i = 0; i < nums.length; i++) {
let temp = nums[i];
while (nums[i] + 1 === nums[i+1]) {
i++;
}
if (temp !== nums[i]) {
record.push(temp + '->' + nums[i]);
} else {
record.push(temp.toString());
}
}
return record;
};

Solution - Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def summary_ranges(nums)
record = []
i = 0

while i < nums.size
start = nums[i]
while i + 1 < nums.size && nums[i] + 1 == nums[i + 1]
i += 1
end

if start != nums[i]
record << "#{start}->#{nums[i]}"
else
record << "#{start}"
end

i += 1
end

record
end

Solution - PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function summaryRanges($nums) {
$record = [];
$i = 0;

while ($i < count($nums)) {
$start = $nums[$i];
$end = $nums[$i];

while ($i + 1 < count($nums) && $nums[$i + 1] === $nums[$i] + 1) {
$end = $nums[$i + 1];
$i++;
}

if ($start === $end) {
$record[] = $start . '';
} else {
$record[] = $start . '->' . $end;
}

$i++;
}

return $record;
}

LeetCode 傳送門 - Summary Ranges