27. Remove Element

inhalin·2021년 2월 22일
0

Leetcode Easy

목록 보기
6/14

문제

Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

배열 nums와 값 val이 주어질 때, nums 배열에서 val을 제거한 배열의 길이를 반환하라.

Example 1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2]
Explanation: Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted.

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 length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.

Constraints:

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

Solution

새로운 배열을 만들지 않고 풀어야 되는 문제다.

  1. 배열의 i번째 요소와 val을 비교해서 값이 같으면 배열의 마지막 요소의 값을 넣고 배열 길이를 1 줄인다. (val은 어차피 제거해야 하는 값이기 때문에 배열의 맨 끝에 넣고 배열 길이를 줄여서 제거해주는 것이다.)

  2. 다시 i번째 요소랑 비교해서 제거해야 하는 값이 아니면 다음 요소로 넘어가고 제거해야 하는 값이면 1번을 반복한다.

class Solution {
    public int removeElement(int[] nums, int val) {
    	int i = 0;
        int len = nums.length;
        while (i < len) {
            if (nums[i] == val) {
                nums[i] = nums[len-1];
                len--;
            } else {
                i++;
            }
        }
        return len;
    }
}

0개의 댓글