코딩테스트(Kotlin)/LeetCode Top Interview 150

[1주차] 27. Remove Element

YJ_Lee 2023. 8. 22. 23:53

https://leetcode.com/problems/remove-element/?envType=study-plan-v2&envId=top-interview-150 

 

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 r

leetcode.com

 


📝 문제

오름차순으로 정렬된 nums 배열에서 val 값과 같은 원소를 모두 삭제, 그 외의 원소의 순서는 유지하라.

그 후, 남은 원소의 개수를 리턴하라.

 

🎈 풀이

(변수명이 'val' 이라 코틀린으로 문제푸는 입장에서 굉장히 마음이 불편하다.)

처음에는 원소를 지운다는 의미를 잘 몰라서 val 과 같은 값의 원소를 nums[i] 범위 밖의 값인 51을 집어넣어은 후 정렬하여

리턴했다. 정답은 맞았지만 조금 찜찜했기에 Custom Judge 조건에 맞추기로 하였다.

 

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];
}

 

주어진 Custom Judge 에서 expectedNums에는 nums에서 val을 지운 결과 배열이 담겨있고, 정답 판별은 이 expectedNums와 주어진 솔루션 메소드를 거친 nums를 비교하여 원소의 값이 같은지만 비교한다. 따라서, val 과 다른 값의 원소만 전부 배열 앞으로 당겨오면 된다. 그 이후 원소의 값은 어떤 값이든 상관 없다.

 

fun removeElement(nums: IntArray, `val`: Int): Int {
    var k = 0
    var idx = 0
    for (i in nums.indices) {
        if (`val` != nums[i]) {
            nums[idx++] = nums[i]   
            k++
        }
    }

    return k
}

 

채점코드를 공개하는 문제는 처음이었는데 출제자의 의도를 명확히 나타내는 만큼 다음부터는 해당 코드에 맞춰서 문제를 풀어봐야겠다.