목차
LeetCode - Problems - Algorithms - 27. Remove Element
Problem Description


My Solution (C#)
public class Solution {
public int RemoveElement(int[] nums, int val)
{
if (nums.Length == 0)
return 0;
int index = 0;
foreach (int num in nums)
{
if (num != val)
{
nums[index] = num;
index++;
}
}
return index;
}
}
26. Remove Duplicates from Sorted Array와 비슷하게 풀었다.
[LeetCode] 26. Remove Duplicates from Sorted Array (C#)
LeetCode - Problems - Algorithms - 26. Remove Duplicates from Sorted Array Problem Description My Solution (C#) public class Solution { public int RemoveDuplicates(int[] nums) { if (nums.Length ==..
j000.tistory.com
다만 26. Remove Duplicates from Sorted Array 문제보다 더 간단하다.
정답은 int 즉, 남아있는 elements의 갯수를 반환하고, parameter로 passed된 nums array의 0부터 제거되지 않은 값을 채우면 된다.
즉, 첫번째 예제 nums = [3, 2, 2, 3], val = 3 이었을 경우 nums는 [2, 2, ?, ?]가 되어야하고, 2를 리턴하면 된다. ?로 표시된 곳은 어떤 숫자가 들어가든 무시한다.
- nums array의 길이가 0이라면 그대로 0을 return한다
- 제거되지 않은 elements의 갯수를 세면서, array를 앞에서부터 채우기 위한 index를 따로 만들어준다.
- nums의 모든 int elements를 확인하기 위한 foreach 반복문을 실행한다.
- 현재 값 num이 val과 다르다면 nums[index]에 num을 assign해준다.
- index 값을 1 증가시킨다.
- index 값을 return 한다.
위 솔루션을 가지고 nums = [3, 2, 2, 3], val = 3 를 parameter로 pass할 경우 nums = [2, 2, 2, 3]이 되고 2가 return된다.

'Problem solving > Algorithms' 카테고리의 다른 글
| [LeetCode] 35. Search Insert Position (C#) (0) | 2021.02.02 |
|---|---|
| [LeetCode] 28. Implement strStr() (C#) (0) | 2021.02.02 |
| [LeetCode] 26. Remove Duplicates from Sorted Array (C#) (0) | 2021.01.29 |
| [LeetCode] 21. Merge Two Sorted Lists (C#) (0) | 2021.01.29 |
| [LeetCode] 20. Valid Parentheses (C#) (0) | 2021.01.26 |