-
leetcode top interview 150 | Remove ElementPS 2023. 8. 23. 17:24
Question
주어진 int 배열 nums에서 val에 해당하는 값을 제자리에서 삭제하고, val과 같지않은 요소의 수를 리턴한다
Accepted Code
class Solution { public int removeElement(int[] nums, int val) { int idx = 0; for(int i=0; i<nums.length; i++){ if(nums[i] != val){ nums[idx++] = nums[i]; } } return idx; } }
solve
제자리에서 삭제하라는 조건이 있기 때문에 새로운 배열을 만들어서 val에 해당하지 않는 값만 넣어주는 방식으로는 풀 수 없다. 같지 않은 요소의 수만 카운팅해서 리턴하지말고 삭제까지 해야한다. 따라서 val과 같지 않을 경우 nums 배열의 first index부터 다시 대입해주는 것으로 생각했다. val 값들은 삭제해야하기 때문에 값이 덧씌워져도 상관없다. 같지않은 요소의 cnt를 확인해주기 위해 idx 변수를 따로 빼고 위치를 순차적으로 증가시켜 리턴해줬다.
https://leetcode.com/problems/remove-element/?envType=study-plan-v2&envId=top-interview-150
Remove Element - LeetCode
Can you solve this real interview question? Remove Element - Given an integer array nums and an integer val, remove all occurrences of val in nums in-place [https://en.wikipedia.org/wiki/In-place_algorithm]. The order of the elements may be changed. Then r
leetcode.com
'PS' 카테고리의 다른 글
leetcode top interview 150 | Two Sum II - Input Array Is Sorted | Two Pointer (0) 2023.08.28 leetcode top interview 150 | Valid Palindrome | Two Pointer (0) 2023.08.28 leetcode top interview 150 | Best Time to Buy and Sell Stock (0) 2023.08.23 leetcode top interview 150 | Remove Duplicates from Sorted Array (0) 2023.08.23 java 프로그래머스 lv3 보석쇼핑 | sliding window + map 활용 (0) 2023.06.29