본문 바로가기
DS & Algo/풀이모음

[leetcode/JS] 27_Remove Element 풀이

by 5kdk 2022. 11. 13.

🎲 문제

 

Remove Element - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

27. Remove Element

Easy


정수 배열 "nums"와 정수 "val"이 주어지면 "nums"에서 발생하는 모든 "val"을 제거합니다. 요소의 상대적 순서는 변경될 수 있습니다.
일부 언어에서는 배열의 길이를 변경할 수 없으므로, 대신 배열의 첫 번째 부분인 "nums"에 결과를 배치해야 합니다. 더 형식적으로, 중복을 제거한 후에 "k" 요소가 있다면, "nums"의 첫 번째 "k" 요소는 최종 결과를 보유해야 합니다. 첫 번째 "k" 요소들 너머로 무엇을 남기는지는 중요하지 않습니다.
최종 결과를 숫자의 첫 번째 "k" 슬롯에 배치한 후 "k"를 반환합니다.

다른 어레이에 추가 공간을 할당하지 마십시오. O(1) 추가 메모리를 사용하여 입력 배열을 수정해야 합니다.

 

더보기

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

 

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

💡 접근 방법

배열 nums에서 val 을 찾아 슬라이스 하는 방식으로 해결

slice를 한 경우 배열 길이가 줄어들기에 인덱스를 하나 줄여서 for loof가 제대로 돌 수 있도록 함 

/**
 * @param {number[]} nums
 * @param {number} val
 * @return {number}
 */
var removeElement = function(nums, val) {
    
    for(let i=0; i < nums.length; i++){
        if(nums[i] === val){
            nums.splice(i, 1);
            i--
        }
    }
    return nums.length;
};
 

 


 

📖 후기

자바스크립트는 배열의 길이가 자유롭기에 문제 중간 내용은 건너뛰어도 됐고,

O(1) 메모리로 해결할 방법만 생각하면 됐다.

배열의 길이만 확인하면 되는 문제였는데 배열을 만지는거보다, 카운팅 방식으로 접근하는게 더 나아 보인다.

 

 

count 변수로 해결한 다른사람의 code
var removeElement = function(nums, val) {
    if(!nums || nums.length < 1){
        return 0;
    }
    
    let count = 0;
    for(let i=0;i<nums.length;i++){
        if(nums[i] == val){
            continue;
        }
        nums[count] = nums[i];
        count++;
    }
    return count;
};

 

 

two point 로 해결한 다른사람의 code
var removeElement = function(nums, val) {
    let left = 0;
    let right = nums.length - 1;
    
    while (left <= right) {
        if (nums[left] === val) {
            nums[left] = nums[right];
            right--;
        }
        else {
            left++;
        }
    }
    
    return left;
};

 

댓글