[java]27. Remove Element

박철진·2023년 8월 23일
0

leetcode

목록 보기
2/25

1. 문제

27. Remove Element

Easy


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

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

2. 문제 해석

정수 배열 nums와 정수 val이 주어졌을 때, nums에서 val이 포함된 모든 항목을 제자리에서 제거합니다. 요소의 순서는 변경될 수 있습니다. 그런 다음 nums에서 val과 같지 않은 요소의 수를 반환합니다.

nums에서 val과 같지 않은 요소의 개수가 k라고 가정할 때, 이를 허용하려면 다음과 같은 작업을 수행해야 합니다:

  • nums의 처음 k 요소에 val과 같지 않은 요소가 포함되도록 배열 nums를 변경합니다. nums의 나머지 요소는 nums의 크기만큼 중요하지 않습니다.
  • k를 반환합니다.

3. 접근 방법

배열에 val과 같은 요소를 제거해야하니깐 배열의 값을 하나씩 꺼내서 val과 비교하는 순차적인 방법으로 접근한다. 배열의 순서는 중요치 않고 k라는 수를 반환할 수 있도록 한다. val과 같은 값이 없어야하니깐 새로운 형태의 배열을 반환하도록 한다.

4. 의사 코드

int k 선언
for (0, nums 길이, 1++) {
	if (i번째 배열의 값과 val 값과 같지 않다면) {
	배열 k번째 값은 원래 있던 배열의 i번째 값
	k 값 1 증가
	}
}
k 반환

5. 문제 풀이

class Solution {
    public int removeElement(int[] nums, int val) {
        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) { // val과 값이 같지 않다면
                nums[k] = nums[i]; // 같지 않는 값의 배열을 값으로 삽입
                k++;
            }
        }
        return k; 
    }
}

새로운 배열을 만들지 않기 위해 기존에 배열에 val과 같지 않는 값들로 삽입하여 nums 배열을 구성하였다.

6. 개선 사항

처음에는 val과 같은 값으로 계속 시도하려고 하니깐 원했던 값과 계속 달라져서 고민이 많았다. 배열의 순서를 중요하지 않고 k라는 값만 잘 꺼내면 된다고 생각해야한다는 문제점에 집중해서 오래 시간이 걸렸다. 문제를 한번 더 잘 읽어보고 기존에 방식이 통하지 않으면 다시 처음부터 고민하는 습관을 들여야겠다.

profile
개발자를 위해 기록하는 습관

0개의 댓글