[LeetCode] 88. Merge Sorted Array, Easy

2025. 3. 10. 15:24·CodingTest/LeetCode
반응형

1. 문제

  • 배열 nums1, nums2가 주어지고, 각각의 길이 m과 n이 주어질 때, 두 배열의 요소를 오름차순으로 정렬하여 nums1 배열에 채워라.
  • 단, nums1 배열은 m+n 길이를 가지고, m만큼은 요소가 채워져있고 나머지 n은 0으로 채워져 있다. 이는 nums2의 길이와 같다.

2. 풀이

/**
 Do not return anything, modify nums1 in-place instead.
 */
function merge(nums1: number[], m: number, nums2: number[], n: number): void {
    let index_1 = m-1; // nums1을 가리키는 포인터
    let index_2 = n-1; // nums2를 가리키는 포인터
    
    for(let i = m + n - 1; i >= 0; i--) { // nums1 마지막부터 탐색.
        if(index_1 < 0) { // 인덱스가 넘어간 경우는 무조건 반대쪽 값을 채택.
            nums1[i] = nums2[index_2];
            index_2--;
        }
        else if(index_2 < 0) {
            nums1[i] = nums1[index_1];
            index_1--;
        }
        else {
            if(nums1[index_1] >= nums2[index_2]) { // 비교해서 큰 값을 넣고 해당 인덱스 감소
                nums1[i] = nums1[index_1];
                index_1--;
            } else {
                nums1[i] = nums2[index_2]; 
                index_2--;
            }
        }
    }
};
  • n 만큼 자리수가 nums1에 존재하니까, 일단 반복은 nums1 길이 만큼 반복한다.
  • 맨 뒤에서 부터 두 배열을 가리키는 포인터를 이용해 큰 값을 찾아 채워 넣는다.
  • 한 쪽이 먼저 다 채워진 경우는 반대쪽 요소로 다 채운다.
  • 또포인터 알고리즘.
저작자표시 (새창열림)
'CodingTest/LeetCode' 카테고리의 다른 글
  • [LeetCode] 26. Remove Duplicates from Sorted Array, Easy
  • [LeetCode] 27. Remove Element, Easy
  • [LeetCode] 1089. Duplicate Zeros, Easy
  • [LeetCode] 977. Squares of a Sorted Array, Easy
뜸부깅
뜸부깅
코딩에 대한 여러 개인적인 생각을 정리하고 공부를 하는 공간입니다!!
  • 뜸부깅
    코오오딩
    뜸부깅
  • 전체
    오늘
    어제
    • Note (429)
      • Skill (31)
        • Java & Spring (9)
        • Javascript & HTML & CSS (0)
        • React (0)
        • Next.js (22)
      • CodingTest (389)
        • 백준 온라인 저지(BOJ) (140)
        • 프로그래머스(Programmers) (79)
        • LeetCode (170)
      • Algorithm & Data Structure (6)
      • [Project] 포트폴리오 (3)
        • Front end (3)
        • Back end (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백준
    next 14
    백준2751
    알고리즘
    TypeScript
    자바
    백준1427
    BOJ
    boj2108
    백준7576자바
    프로그래머스
    component-scan
    Java
    medium
    meidum
    leetcode 2236
    Easy
    boj1427
    백준7576
    백준1260
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[LeetCode] 88. Merge Sorted Array, Easy
상단으로

티스토리툴바