Problem solving/Algorithms

[LeetCode] 27. Remove Element (C#)

Young_A 2021. 1. 30. 12:47

목차

    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를 리턴하면 된다. ?로 표시된 곳은 어떤 숫자가 들어가든 무시한다.

     

    1. nums array의 길이가 0이라면 그대로 0을 return한다
    2. 제거되지 않은 elements의 갯수를 세면서, array를 앞에서부터 채우기 위한 index를 따로 만들어준다.
    3. nums의 모든 int elements를 확인하기 위한 foreach 반복문을 실행한다.
      1. 현재 값 num이 val과 다르다면 nums[index]에 num을 assign해준다.
      2. index 값을 1 증가시킨다.
    4. index 값을 return 한다.

    위 솔루션을 가지고 nums = [3, 2, 2, 3], val = 3 를 parameter로 pass할 경우 nums = [2, 2, 2, 3]이 되고 2가 return된다.

     

    LeetCode - 27. Remove Element