알고리즘
[leetcode] 27. Remove Element
개발정리
2021. 11. 9. 22:53
Description
정수로 이루어진 nums 배열과 특정 값 val 이 매개변수로 주어졌을때 배열 안에 val 과 동일한 값이 있으면 해당 배열에서 제거한 후 배열안에 유효한 값이 몇개인지를 출력하는 문제
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Success
cnt와 i 라는 두 개의 변수를 두어 nums[i] 의 값이 val 과 같지 않으면 cnt 가 가르키는 인덱스로 값을 채워 나간다. 그렇게 값을 채워나가다 보면 cnt 에는 val 의 값에 해당되지 않는 유효한 값들만 존재하게되고 cnt 는 유효한 값의 길이를 담고 있게 된다.
class Solution {
public int removeElement(int[] nums, int val) {
int cnt=0;
for(int i=0; i<nums.length; i++) {
if(nums[i] != val) {
nums[cnt] = nums[i];
cnt++;
}
}
return cnt;
}
}
출처
Explore - LeetCode
LeetCode Explore is the best place for everyone to start practicing and learning on LeetCode. No matter if you are a beginner or a master, there are always new topics waiting for you to explore.
leetcode.com