PS/LeetCode

LeetCode / Array / 228번 / Summary Ranges / JS

KimMinJun 2023. 6. 17. 13:50

< 문제 바로가기 >

 

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

 

< 문제 간단설명 >

연속수를 이루는 모든 범위를 배열에 담아서 반환한다.

 

/**
 * @param {number[]} nums
 * @return {string[]}
 */
var summaryRanges = function (nums) {
  let result = [];

  let i = 0;
  while (i < nums.length) {
    let start = nums[i];

    // 연속수가 아닐때까지 인덱스 증가
    while (nums[i + 1] === nums[i] + 1) {
      i += 1;
    }

    let end = nums[i];

    // 시작수와 끝수가 같다면 하나만 결과에 추가
    result.push(start === end ? `${start}` : `${start}->${end}`);
    i += 1;
  }

  return result;
};