09.21 프로그래머스 코딩테스트

곽민규·2023년 9월 21일
0

코딩테스트 연습

목록 보기
12/12

제일 작은 수 제거하기

문제 설명

정수를 저장한 배열, arr 에서 가장 작은 수를 제거한 배열을 리턴하는 함수, solution을 완성해주세요. 단, 리턴하려는 배열이 빈 배열인 경우엔 배열에 -1을 채워 리턴하세요. 예를들어 arr이 [4,3,2,1]인 경우는 [4,3,2]를 리턴 하고, [10]면 [-1]을 리턴 합니다.

제한 조건

arr은 길이 1 이상인 배열입니다.
인덱스 i, j에 대해 i ≠ j이면 arr[i] ≠ arr[j] 입니다.

나의 답안

using System.Linq;

public class Solution {
    public int[] solution(int[] arr) {
        int[] answer = new int[] {};
        int min = arr.Min();
         answer = arr.Where(num => num != min).ToArray();
        
        if (answer.Length == 0) {
            answer = new int[] {-1};
        }
        
        return answer;
    }
}

Min 함수로 최솟값을 구하고 Where 문과 ToArray를 통해 조건에 맞는 새 배열을 리턴 받았다.

Where 함수는 필터링할 소스와 함수를 받아 소스의 각 요소를 함수 조건에 맞춰 필터링한 값을 리턴한다.

https://learn.microsoft.com/ko-kr/dotnet/api/system.linq.enumerable.where?view=net-7.0#system-linq-enumerable-where-1(system-collections-generic-ienumerable((-0))-system-func((-0-system-boolean)))

ToArray는 IEnumerable 형식 반환 값에 맞춰 사용된다.

https://learn.microsoft.com/ko-kr/dotnet/api/system.linq.enumerable.toarray?view=net-7.0#system-linq-enumerable-toarray-1(system-collections-generic-ienumerable((-0)))

profile
취준생

0개의 댓글