코딩공부/프로그래머스

※[프로그래머스]Lv.2 가장 큰 수C#(문자열 CompareTo 정렬, 시간복잡도 오류)

usingsystem 2023. 8. 1. 14:24
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/42746

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

처음에 순열을 통하여 접근하는 방법을 생각했으나 시간복잡도 오류가 발생하였다.

문자열 비교를 통해 정렬 하여 문제를 해결하였다.

소스코드1(시간복잡도 오류)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Solution {
       List<int> list = new List<int>();
        public  string solution(int[] numbers)
        {
            perm(numbers, 0);
            return list.Max().ToString() ;
        }
         void perm (int[] arr, int depth )
        {
            if( arr.Length == depth )
            {
                StringBuilder strArr = new StringBuilder();
                for (int i = 0; i < arr.Length; i++)
                    strArr.Append(arr[i]); 
                list.Add(int.Parse(strArr.ToString()));
            }
            else
            {
                for (int i = depth; i < arr.Length; i++)
                {
                    int temp = arr[depth];
                    arr[depth] = arr[i];
                    arr[i] = temp;

                    perm(arr, depth + 1);

                    temp = arr[depth];
                    arr[depth] = arr[i];
                    arr[i] = temp;
                }
            }
        }
}

소스코드2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Solution
{
    public string solution(int[] numbers)
    {
        List<string> strNumbers = new List<string>();

        for (int i = 0; i < numbers.Length; i++)
            strNumbers.Add(numbers[i].ToString());

        strNumbers.Sort((a, b) => (b + a).CompareTo(a + b));

        string answer = string.Join("", strNumbers);

        return answer[0] == '0' ? "" : answer;
    }
}
728x90