본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 228. Summary Ranges

반응형

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

 

Summary Ranges - LeetCode

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

leetcode.com

구현 문제였습니다.

📕 풀이방법

📔 풀이과정

정답 vector ans를 선언해줍니다.2차원 for loop를 수행해서 등차가 1보다 큰 값의 index를 찾아 piv에 저장합니다.현재 index가 piv와 다르다면 범위가 형성되어 있으므로 "->"가 포함된 범위 문자열을 저장합니다.아니라면 자기 자신이므로 그대로 ans에 넣어줍니다.

 

📔 정답출력

만든 vector ans를 반환합니다.


📕 Code

📔 C++

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        vector <string> ans;
        for(int curIdx = 0; curIdx < nums.size(); curIdx++) {
            int piv = curIdx;
            long long cnt = nums[curIdx];
            for(int nextIdx = curIdx; nextIdx < nums.size(); nextIdx++) {
                if(nums[nextIdx] != cnt) break;
                cnt++;
                piv = nextIdx;
            }
            if(curIdx != piv) {
                ans.push_back(to_string(nums[curIdx]) + "->" + to_string(nums[piv]));
            }
            else {
                ans.push_back(to_string(nums[curIdx]));
            }
            curIdx = piv;
        }
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.