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;
};'PS > LeetCode' 카테고리의 다른 글
| LeetCode / Tree / 530번 / Minimum Absolute Difference in BST / JS (0) | 2023.06.17 | 
|---|---|
| LeetCode / Matrix / 2352번 / Equal Row and Column Pairs / JS (0) | 2023.06.17 | 
| LeetCode / Design / 155번 / Min Stack / JS (0) | 2023.05.14 | 
| LeetCode / Design / 232번 / Implement Queue using Stacks / JS (0) | 2023.05.14 |