leetcode
[leetcode] 27. Remove Element
누누01
2024. 3. 25. 16:00
728x90
https://leetcode.com/problems/remove-element/?envType=study-plan-v2&envId=top-interview-150
문제
정수 배열 nums 와 정수 val 이 주어졌을 때, nums 배열에서 val 을 제거 하고 제거한 배열의 길이를 출력하는 문제이다.
단, 문제에서 in-place 방식으로 풀 것을 요구하고 있다.
in-place 방식은 새로운 자료구조를 추가하지 않고 주어진 자료구조에서 문제를 해결하는 방식을 말한다.
풀이
class Solution {
public int removeElement(int[] nums, int val) {
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == val) {
continue;
}
nums[index] = nums[i];
index++;
}
return index;
}
}