nums 란 int 배열에서 int val 의 숫자만 제거하기
제거된 숫자 이외의 남은 숫자들은 nums 배열 앞에서부터 배치되게 한다.
배치 순서는 상관 없다. 배열의 크기는 변경할 수 없다. 추가로 배열을 할당해서 풀 수 없다. nums를 수정해야 한다.
남은 숫자의 개수를 반환해야 한다.
Example
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).
어제 풀었던 문제의 해결방법과 유사해서 금방 풀 수 있었다
탐색하면서 val과 같은 값의 인덱스에 insertidx가 머물게 하고 val과 다른 값을 찾으면 대입하는 방식으로 해결하였다 이때 i가 insertidx 보다 앞서있을때 값이 대입되게 하였다
class Solution {
public int removeElement(int[] nums, int val) {
int insertidx = 0;
for(int i = 0; i < nums.length; ++i)
{
if(nums[i] != val)
{
if(i!=insertidx)
nums[insertidx] = nums[i];
insertidx++;
}
}
return insertidx;
}
}