logoStephen's 기술블로그

포스트 검색

제목, 태그로 포스트를 검색해보세요

[LeetCode] Remove Element

[LeetCode] Remove Element
CodingTest
성훈 김
2025년 8월 22일
목차

문제 링크

Remove Element - LeetCode
Can you solve this real interview question? Remove Element - Given an integer array nums and an integer val, remove all occurrences of val in nums in-place [https://en.wikipedia.org/wiki/In-place_algorithm]. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val. Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things: * Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums. * Return k. Custom Judge: The judge will test your solution with the following code: int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums[i] == expectedNums[i]; } If all assertions pass, then your solution will be accepted.   Example 1: Input: nums = [3,2,2,3], val = 3 Output: 2, nums = [2,2,_,_] Explanation: Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). Example 2: Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 5, nums = [0,1,4,0,3,_,_,_] Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores).   Constraints: * 0 <= nums.length <= 100 * 0 <= nums[i] <= 50 * 0 <= val <= 100
Remove Element - LeetCode

문제 요구 조건

  • nums와 val이 같은 경우 제거하고 배열의 앞 부분을 val랑 같지 않은 값들로 재구성한다.
  • val이랑 같이 다른 배열 앞부분은 정렬되지 않아도 된다.
  • 배열을 직접 수정해야된다. (in-place)
  • 검증은 val이랑 같지 않은 요소의 갯수 k를 리턴하고, nums배열이 val값이 없는지 검증한다.

나의 문제 풀이

이전에 풀었던 방식과 마찬가지로 배열을 직접 수정하는데에는 Two Pointer 기법이 제일 잘 어울린다고 생각했다. 그래서 val과 같지 않은 요소를 덮어씌우는 index와 순회하는 index가 필요하다. 즉 pointer와 for문의 i요소가 있으면 된다.
 
  1. pointer를 0으로 초기화한다.
  1. 각 요소를 순회하는 for문을 만든다.
  1. 각 순회에서 nums[i]val이랑 같지 않으면, 해당 요소를 nums[pointer]로 덮어씌운다.
  1. 그리고 pointer를 1 증가시킨다.
 
나의 문제 풀이
JavaScript
/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function (nums, val) {
    let pointer = 0;

    for (let i = 0; i < nums.length; i++) {
        if (nums[i] !== val ) {
            nums[pointer] = nums[i]
            pointer++
        }
    }
    return pointer
};
 

정답 문제 풀이

현재 방법이 제일 효율적이다.