반응형
https://leetcode.com/problems/summary-ranges/description/
Summary Ranges - LeetCode
Can you solve this real interview question? 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 arr
leetcode.com
1의 차이로 연속된 구간을 하나로 묶어주었습니다.
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
if(nums.empty()) return {};
int s = nums[0], e = nums[0];
vector<string> res;
for(int n : nums) {
if(n > e + 1) {
res.push_back(s == e ? to_string(s) : to_string(s) + "->" + to_string(e));
s = e = n;
} else {
e = n;
}
}
res.push_back(s == e ? to_string(s) : to_string(s) + "->" + to_string(e));
return res;
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 530. Minimum Absolute Difference in BST (0) | 2023.06.14 |
---|---|
LeetCode 2352. Equal Row and Column Pairs (0) | 2023.06.13 |
LeetCode 1146. Snapshot Array (0) | 2023.06.11 |
LeetCode 1351. Count Negative Numbers in a Sorted Matrix (0) | 2023.06.08 |
LeetCode 1318. Minimum Flips to Make a OR b Equal to c (0) | 2023.06.07 |