[LeetCode] 27. Remove Element

조수훈·2023년 8월 22일

Algorithm

목록 보기
4/5
post-thumbnail

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:

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).

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

Solution

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        while nums.count(val):
            nums.remove(val)

단순히 nums 배열안에 val값이 있다면 nums 에서 val값을 제거하는 코드를 짰다. 하지만 remove 함수와 count 함수는 결국 배열 처음부터 끝까지 돌아야하므로 O(N) 의 시간이 소요된다. 따라서 해당 코드는 O(N^2) 의 시간이 소요될것이다.

Develop

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        idx = 0
        for i in range(len(nums)):
            if nums[i] != val:
                nums[idx] = nums[i]
                idx +=1
        return idx

다른 사람의 풀이를 참고하여 다시 작성한 코드이다. two pointer 알고리즘과 비슷한느낌이다. 두개의 포인터 i,idx는 각각 nums 의 처음을 가르킨다.
i 는 for 문에서 증가한다.
nums[i]가 val와 다를때, nums[idx]에 nums[i]를 대입하고 idx의 값을 하나 증가시킨다.

profile
잊지 않기 위해 기록하기

0개의 댓글