[leetcode #228] Summary Ranges

Seongyeol Shin·2022년 2월 28일
0

leetcode

목록 보기
158/196
post-thumbnail
post-custom-banner

Problem

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³¹ <= nums[i] <= 2³¹ - 1
・ All the values of nums are unique.
・ nums is sorted in ascending order.

Idea

주어진 수들의 범위를 string으로 표현하라는 문제다.

연속된 정수가 아닐 경우 지금까지 계산했던 범위를 추가하고, 연속된 정수인 경우 end point를 현재 수로 정하면 된다.

전체 수를 탐색하고 난 뒤 start point와 end point를 비교해 마지막 범위로 넣으면 된다.

Solution

class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> res = new ArrayList<>();

        if (nums.length == 0) {
            return res;
        }

        int startingPoint = nums[0];
        int endingPoint = nums[0];
        for (int i=1; i < nums.length; i++) {
            if (nums[i] - nums[i-1] != 1) {
                if (endingPoint == startingPoint) {
                    res.add(String.format("%d", endingPoint));
                } else {
                    res.add(String.format("%d->%d", startingPoint, endingPoint));
                }
                startingPoint = nums[i];
                endingPoint = nums[i];
            } else {
                endingPoint = nums[i];
            }
        }

        if (endingPoint == startingPoint) {
            res.add(String.format("%d", endingPoint));
        } else {
            res.add(String.format("%d->%d", startingPoint, endingPoint));
        }

        return res;
    }
}

Reference

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

profile
서버개발자 토모입니다
post-custom-banner

0개의 댓글