[프로그래머스] 제일 작은 수 제거하기

김유원·2024년 1월 17일
0

📝24.01.17

🔗 문제 : https://school.programmers.co.kr/learn/courses/30/lessons/12935

문제 설명

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

[C#] 내가 작성한 풀이

1) Linq 활용 풀이

오답

1개의 테스트 케이스에서 시간 초과 오류가 났다.
아마도 num != arr.Min()을 매번 하는 데에서 시간 초과가 일어나지 않았을까?

using System;
using System.Linq;

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

그래서 이 방향으로 수정하였더니 문제없이 해결되었다.

정답

using System;
using System.Linq;

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

이를 Chat-GPT에게 물어본 결과 내 예상대로 해당 문제가 맞았다.

2) list로 치환하여 풀이

using System;
using System.Linq;
using System.Collections.Generic;

public class Solution {
    public int[] solution(int[] arr) {
        int min = arr.Min();

        List<int> answer = new List<int>();

        for(int i = 0; i < arr.Length; i++) {
            if(arr[i] != min) answer.Add(arr[i]);
        }

        if(answer.Count == 0) answer.Add(-1);

        return answer.ToArray();
    }
}

인상적이었던 C# 남의 풀이가 없었다.

C++의 내가 작성한 풀이는 C#의 2) list 치환 풀이와 동일한 방법으로 풀이하였다.

[C++] 남이 작성한 풀이

min_element를 적절히 활용한풀이다.

#include <algorithm>
#include <vector>
using namespace std;

vector<int> solution(vector<int> arr) {
    if (arr.size() == 1) {
        return { -1 };
    }
    arr.erase(min_element(arr.begin(), arr.end()));
    return arr;
}
profile
개발 공부 블로그

0개의 댓글

관련 채용 정보