[LeetCode] 2605. Form Smallest Number From Two Digit Arrays

Chobby·2025년 11월 21일

LeetCode

목록 보기
770/800

😎풀이

  1. nums1nums2 오름차 순 정렬
  2. Set객체를 통해 정렬된 각 배열 변환
    2-1. 교집합이 있는지 탐색하며 최솟값 갱신
  3. 정렬된 nums1nums2 순회
  4. 더 작은 수를 십의 자리로, 더 큰 수를 일의 자리로 설정하여 두 자리로 만들 수 있는 최솟값 생성
  5. 최솟값 갱신
  6. 탐색된 최솟값 반환
function minNumber(nums1: number[], nums2: number[]): number {
    let min = Infinity
    const sorted1 = nums1.toSorted((a, b) => a - b)
    const sorted2 = nums2.toSorted((a, b) => a - b)
    const set1 = new Set(sorted1)
    const set2 = new Set(sorted2)
    for(const num of set1) {
        if(set2.has(num)) {
            min = Math.min(min, num)
        }
    }
    const len = Math.min(set1.size, set2.size)
    for(let i = 0; i < len; i++) {
        const num1 = sorted1[i]
        const num2 = sorted2[i]
        const less = Math.min(num1, num2)
        const more = Math.max(num1, num2)
        const strNum = String(less) + String(more)
        const num = Number(strNum)
        min = Math.min(min, num)
    }
    return min
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글