본문 바로가기
LeetCode

[LeetCode] 27. Remove Element

by JungSeung 2023. 10. 27.
728x90

https://leetcode.com/

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. 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:

nput: 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

 

Code :

var removeElement = function(nums, val) {
    let r = 0; // 유효한 요소의 개수를 나타내는 변수 r을 0으로 초기화

    for (let i = 0; i < nums.length; i++) {
        // 현재 요소가 val과 같지 않으면 nums[r]에 복사하여 유효한 요소로 처리
        if (nums[i] !== val) {
            nums[r] = nums[i];
            r++;
        }
    }

    return r; // 유효한 요소의 개수 r을 반환
};

 

Solutions Code :

function removeElement(nums, val) {
    // val이 아닌 요소의 개수를 세는 변수
    let count = 0;
    // 배열의 모든 요소를 순회한다.
    for (let i = 0; i < nums.length; i++) {
        // 만약 현재 요소가 val이 아니라면
        if (nums[i] !== val) {
            // 현재 위치에 해당하는 요소를 count 위치에 덮어쓴다.
            nums[count++] = nums[i];
        }
    }
    // 특정 값이 제외된 배열의 길이를 반환한다.
    return count;
}

 

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90