본문 바로가기
Computer Science/알고리즘

leetcode 228) Summary Ranges

by eeeun:) 2022. 2. 28.
반응형

LV. Easy 😎

https://leetcode.com/problems/summary-ranges/

 

Summary Ranges - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

문제

You are given a sorted unique integer array nums.

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.

Each range [a,b] in the list should be output as:

  • "a->b" if a != b
  • "a" if a == b

 

Example 1:

Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Explanation: The ranges are:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"

Example 2:

Input: nums = [0,2,3,4,6,8,9]
Output: ["0","2->4","6","8->9"]
Explanation: The ranges are:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"

 

Constraints:

  • 0 <= nums.length <= 20
  • -2^31 <= nums[i] <= 2^31 - 1
  • All the values of nums are unique.
  • nums is sorted in ascending order.

 

문제 해결법

start를 두어 nums를 한번 돌면서 연속된 범위를 찾아서 ans 백터에 추가해줬다.

start와 연속된 값이 아니면 범위 안의 수가 하나 있는지 확인 후 수가 1개이면 "nums[start]", 2개 이상이면 "nums[start]->nums[end]"로 string를 만들어줬다.

 

해결 코드

class Solution {
private:
	void put_string(vector<string> &ans, int start, int end, vector<int>& nums) {
		string temp = "";

		if (start == end - 1)
			temp = to_string(nums[start]);
		else
			temp = to_string(nums[start]) + "->" + to_string(nums[end - 1]);
		ans.push_back(temp);
	}
public:
	vector<string> summaryRanges(vector<int>& nums) {
		vector<string> ans;
		int size = nums.size();
		if (size == 0)
			return ans;
		int start = 0;

		for (int i = 1; i < size; ++i) {
			if (nums[start] + (i - start) != nums[i]) {
				put_string(ans, start, i, nums);
				start = i;
			}
		}
		put_string(ans, start, size, nums);
		return ans;
	}
};

728x90

'Computer Science > 알고리즘' 카테고리의 다른 글

leetcode 799) Champagne Tower  (0) 2022.03.04
leetcode 338) Counting Bits  (0) 2022.03.01
leetcode 165) Compare Version Numbers  (0) 2022.02.25
leetcode 148) Sort List  (0) 2022.02.24
leetcode 133) Clone Graph  (0) 2022.02.23

댓글