[LeetCode] 27. Remove Element, Easy

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

1. 문제

  • 배열 nums와 값 val이 주어질 때, val와 일치하지 않는 요소들을 nums 배열 앞에 나열한 뒤, 길이를 반환하라.
  • val와 일치하지 않는 요소들을 앞에 나열 시킬 때, 순서는 상관없고 이후에 어떤 요소가 오든 상관없다.

2. 해결

function removeElement(nums: number[], val: number): number {
    
    let index = 0;
    let end_index = nums.length -1;
    
    while (index <= end_index) {
        while(nums[end_index] === val && end_index > index) end_index--;

        if(nums[index] === val) {
            nums[index] = nums[end_index];
            nums[end_index] = val
            end_index--;
        }    
        index++;
    }
    
    return end_index+1;
};
  • 마찬가지로 주어진 배열을 수정해야 하고, 효율적인 탐색을 위해 투포인터를 사용해보자.
  • index는 0번 인덱스부터, end_index는 배열의 마지막 요소부터 시작해서 만날 때 까지 반복한다.
  • 현재 index 값이 val과 동일하면, end_index의 값을 가져와 꽂는다. 이 때, end_index의 요소가 val인 경우도 있을 수 있으니까 걸러주는 작업을 통해 end_index는 먼저 조정한다.

 

저작자표시 (새창열림)
'CodingTest/LeetCode' 카테고리의 다른 글
  • [LeetCode] 1346. Check If N and Its Double Exist, Easy
  • [LeetCode] 26. Remove Duplicates from Sorted Array, Easy
  • [LeetCode] 88. Merge Sorted Array, Easy
  • [LeetCode] 1089. Duplicate Zeros, 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)
  • 블로그 메뉴

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

  • 공지사항

  • 인기 글

  • 태그

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

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[LeetCode] 27. Remove Element, Easy
상단으로

티스토리툴바