개발일지

27. Remove Element 본문

Algorithm

27. Remove Element

wa_n 2023. 8. 24. 16:24
728x90
반응형

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.

제거하기 (Remove Element)

주어진 정수 배열 **nums**와 정수 **val**에 대하여, 배열 **nums**에서 **val**의 모든 발생을 제자리에서 제거하세요. 요소의 순서는 변경될 수 있습니다. 그리고 **val**과 같지 않은 **nums**의 요소 수를 반환하세요.

**nums**에서 **val**과 같지 않은 요소의 수를 **k**라고 가정할 때, 통과하려면 다음과 같이 해야 합니다:

  • nums 배열을 변경하여 **nums**의 첫 k 요소가 **val**과 다른 요소를 포함하도록 합니다. **nums**의 크기나 나머지 요소는 중요하지 않습니다.
  • **k**를 반환합니다.

Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // 입력 배열
int val = ...; // 제거할 값
int[] expectedNums = [...]; // 올바른 길이를 가진 예상 답변.
                            // val과 같은 값이 없도록 정렬됩니다.

int k = removeElement(nums, val); // 구현한 함수 호출

assert k == expectedNums.length;
sort(nums, 0, k); // nums의 첫 k 요소 정렬
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

문제접근

주어진 배열과 정수를 이용해서 배열에 주어진 정수를 제거한 후 들어가 있는 값의 요소 수를 반환하는 걸로 이해했습니다.

var removeElement = function(nums, val) {
    k = 0
    for(let i=0; i < nums.length; i++){
        if(nums[i] === val){
            nums.
     
        }
       console.log(nums)
    }
     return k
};

문제를 일치하지 않은 요소수를 반환하는줄 알고 k의 값을 카운트해서 반환했는데 주어진 값을 제외한 배열을 반환하는 거였다

배열에서 일치하는 요소를 제거하는 방식을 사용하기 위해 splice()를 사용하였습니다. splice() 매개변수로 start, deleteCount, item1 item2 … (배열에 추가할 요소들 이 값이 없으면 삭제만 합니다.)을 넣어서 사용할 수 있다.

삭제해야 할 값과 일치하면 그 자리의 인덱스 값을 기준으로 1가지 요소만 삭제한다고 하고 인덱스 값을 빼준다 splice()를 사용해서 삭제하면 요소가 왼쪽으로 한 칸씩 이동한다. 그래야 건너뛰어 넘는 값이 없이 다 확인 가능하다.

 if(nums[i] === val){
           nums.splice(i,1)
            i--  

정답

var removeElement = function(nums, val) {
    k = 0
    for(let i=0; i < nums.length; i++){
        if(nums[i] === val){
           nums.splice(i,1)
            i--
        }else{
            k++
        }
    
    }
     return k
};
728x90
반응형

'Algorithm' 카테고리의 다른 글

88. Merge Sorted Array  (0) 2023.08.24
컨트롤 제트 .py  (0) 2023.08.10
최솟값 만들기  (0) 2023.05.17
로또의 최고 순위와 최저 순위  (0) 2023.04.03
문자열 내 마음대로 정렬하기  (0) 2023.04.03