카테고리 없음

(Leet Code c++)Summary Ranges

naeunchan 2021. 7. 26. 11:24
728x90
반응형

228. Summary Ranges

 

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"

Example 3:

Input: nums = [] Output: []

Example 4:

Input: nums = [-1] Output: ["-1"]

Example 5:

Input: nums = [0] Output: ["0"]

 

Constraints:

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

nums의 원소 사이즈가 INT형이기 때문에,

long long 형으로 min과 max를 선언해준다.

 

min과 max는 nums[i]로 초기화하여 시작.

현재 인덱스와 다음 인덱스의 차가 1이라면 요약을 할 수 있다는 뜻이다.

그러므로 max = nums[j]로 하여 값을 갱신해 나가도록 한다.

(i++을 해주어 요약 후의 인덱스로 넘어가도록 한다.)

 

만약 max와 nums[j]의 차가 1이 아니라면 바로 break.

 

이후 max - min을 구하여 값이 0이라면 요약을 할 수 없다는 뜻이므로 min을 push.

 

max - min이 1 이상이라면 "(min)->(max)"를 push.

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector<string> answer;
        
        for(int i = 0; i < nums.size(); i++){
            long long min = nums[i];
            long long max = nums[i];
            
            for(int j = i + 1; j < nums.size(); j++){
                if(nums[j] - max == 1){
                    max = nums[j];
                    i++;
                }
                else{
                    break;
                }
            }
            
            if(max - min){
                answer.push_back(to_string(min) + "->" + to_string(max));
            }
            else{
                answer.push_back(to_string(min));
            }
        }
        
        return answer;
    }
};
728x90
반응형