https://leetcode.com/problems/remove-element/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Algorithm
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
위와 같이 val을 제거한 배열을 리턴해야한다.각 원소를 순회하면서,원소가 val과 값이 다르다면 l pointer 인덱스 위치에 값을 넣고,1을 증가한다.
Python
class Solution(object):
def removeElement(self, nums, val):
l = 0
for i in range(len(nums)):
if val != nums[i]:
nums[l] = nums[i]
l += 1
return l
Java
class Solution {
public int removeElement(int[] nums, int val) {
int l = 0;
for(int i = 0; i< nums.length; i++) {
if(nums[i] != val) {
nums[l++] = nums[i];
}
}
return l;
}
}
'자료구조&알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 1091. Shortest Path in Binary Matrix (0) | 2024.03.21 |
---|---|
[LeetCode] 1171. Remove Zero Sum Consecutive Nodes from Linked List (0) | 2024.03.12 |
[LeetCode] 26. Remove Duplicates from Sorted Array (0) | 2023.09.18 |