[LeetCode][Java] Remove Element

최지수·2021년 11월 24일
0

Algorithm

목록 보기
29/77
post-thumbnail

문제

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.

제한사항

  • 0 \leq nums.length \leq 100
  • 0 \leq nums[i] \leq 50
  • 0 \leq val \leq 100

접근

val을 제외한 배열을 반환하는 함수를 구현하는 문제입니다.

Remove Duplicates from Sorted Array처럼 변환 후 배열 개수를 반환해 해당 크기만큼 원소를 출력하여 크기를 넘긴 원소는 따로 예외 처리하지 않습니다.

그리고 다행히도 따로 정답과 동일한 결과가 아니라 내부에 원소만 있으면 답으로 처리되는 문제네요.

원소 값이 val일 경우 우측 배열의 모든 원소를 swapping해주면 됩니다.

다만 주의할 점은 그럴때마다 길이가 감소되고, swapping 과정 후 val를 담은 배열의 위치가 현재 인덱스와 같아 지는 경우가 있어, 이를 조심하고 푸시면 됩니다.

답안

class Solution {
    public int removeElement(int[] nums, int val) {

        int ret = nums.length;

        for(int i = 0; i < ret; ){
            if(nums[i] == val){
                for(int j = i + 1; j < nums.length; ++j)
                    nums[j - 1] = nums[j];
                --ret;
            }
            else{
                ++i;
            }
        }

        return ret;
    }

}
profile
#행복 #도전 #지속성

0개의 댓글