반응형

 

 

 

 

풀이코드

#include <string>
#include <vector>
#include <unordered_map>

using namespace std;

#define EXIST 1
#define FAIL 0

string GetAnswer(const vector<string>&, const vector<string>&);

string solution(vector<string> participant, vector<string> completion) {
    string answer = GetAnswer(participant, completion);
    return answer;
}

string GetAnswer(const vector<string>& participant, const vector<string>& completion)
{
    string returnStr = "";
    unordered_map<string, int> map;
    for (int i = 0; i < completion.size(); i++)
    {
        if (map.count(completion[i]) != EXIST)
        {
            map.insert(make_pair(completion[i], 1));
        }
        else
        {
            map[completion[i]]++;
        }
    }

    for (int i = 0; i < participant.size(); i++)
    {
        if(map.count(participant[i]) != EXIST)
        {
            returnStr = participant[i];
            break;
        }
        else
        {
            map[participant[i]]--;

            if (map[participant[i]] < FAIL)
            {
                returnStr = participant[i];
                break;
            }
        }
    }

    return returnStr;
}
  • 완주한 선수들의 목록을 map으로 묶어서, 참가한 선수들 목록 대상으로 탈락한 선수의 이름을 반환한다.
  • map에 키값이 없으면 탈락한 선수이므로 해당 선수의 이름을 반환.
  • map에 키값이 있으면 value값을 감소시킨 뒤, value가 음수가 되면 해당 이름의 선수가 탈락한 것이므로 해당 선수의 이름을 반환.

 

 

 

기타

- 없음.

 

 

 

 

 

반응형

'Stack > Coding test' 카테고리의 다른 글

[C++ / Lv2] 위장  (0) 2022.02.07
[C++ / Lv2] 전화번호 목록  (0) 2022.02.05
[C++ / Lv2] 문자열 압축  (0) 2022.02.02
[C# / Lv2] H-Index  (0) 2022.01.19
[C# / Lv2] 가장 큰 수  (0) 2022.01.18
반응형

 

 

 

 

풀이코드

#include <string>
#include <vector>

using namespace std;

int GetTotElementSize(vector<string>);
int GetAnswer(string str);

int solution(string s) {
    int answer = GetAnswer(s);
    return answer;
}

int GetAnswer(string str)
{
    int resultSize = str.length();
    vector<string> resultVector;
    string currentStr, compareStr;

    for (int i = 1; i <= str.length() / 2; i++)
    {
        currentStr = str.substr(0, i);
        int compareCount = 1;
        int compareStart = i;

        while (compareStart < str.length())
        {
            compareStr = str.substr(compareStart, i);

            if (currentStr == compareStr)
            {
                compareCount++;
            }
            else
            {
                if (compareCount > 1)
                {
                    resultVector.push_back(to_string(compareCount));
                }
                resultVector.push_back(currentStr);

                currentStr = str.substr(compareStart, i);
                compareCount = 1;
            }
            compareStart += i;
        }

        if (compareCount > 1)
        {
            resultVector.push_back(to_string(compareCount));
        }
        resultVector.push_back(currentStr);

        int tot = GetTotElementSize(resultVector);
        resultSize = resultSize > tot ? tot : resultSize;
        resultVector.clear();
    }

    return resultSize;
}

int GetTotElementSize(vector<string> vecStr)
{
    int returnValue = 0;
    for(int i = 0; i < vecStr.size(); i++)
    {
        returnValue += vecStr[i].length();
    }
    return returnValue;
}
  • 문자열의 패턴을 비교해서 수를 메기는 형태이기 때문에 첫번째 반복문에서 모든 문자열길이만큼의 루프를 돌 필요가 없다.
  • while문의 각 루프마다 이전에 패턴 비교를 위해 잘라둔 문자열과 비교해서 같으면 compareCount를 증가시키고 다르면 비교 패턴을 수정해준다.

 

 

 

 

기타

- 잠깐 C++ 못했다고 레퍼런스가 기억이나지 않아서 비주얼스튜디오 켜서 작성함.

 

 

 

 

 

반응형

'Stack > Coding test' 카테고리의 다른 글

[C++ / Lv2] 전화번호 목록  (0) 2022.02.05
[C++ / Lv1] 완주하지 못한 선수  (0) 2022.02.04
[C# / Lv2] H-Index  (0) 2022.01.19
[C# / Lv2] 가장 큰 수  (0) 2022.01.18
[C# / Lv1] k번째 수  (0) 2022.01.17
반응형

 

 

 

 

풀이코드

using System;

public class Solution {
    public int solution(int[] citations) {
        int answer = GetAnswer(citations);
        return answer;
    }
    
    private int GetAnswer(int[] citations)
    {
        Array.Sort(citations, (a, b) => {return b.CompareTo(a);});
        if(citations[0] == 0)
        {
            return 0;
        }
        
        int returnValue = 0;
        for(int i = 0; i < citations.Length; i++)
        {
            if(citations[i] < i + 1)
            {
                returnValue = i;
                break;
            }
        }
        
        return returnValue == 0 ? citations.Length : returnValue;
    }
}
  • 내림차순 정렬을 한 뒤, 첫번째 원소가 0이면 H-Index는 0이다.
  • 인용이 한번이상 되었다면 발표한 논문의 수와 인용된 수를 비교해서 인용된 수가 논문의 수보다 작으면 index값이 H-Index가 된다.
  • 발표한 모든 논문의 인용된 수가 같으면 논문의 수가 H-Index가 된다.

 

 

 

기타

- H-Index만 제대로 이해하면 어려운 문제는 아닌데, 태어나서 처음보는 개념이라 헤맸다.

- H-Index

 

h-index - Wikipedia

From Wikipedia, the free encyclopedia Jump to navigation Jump to search Metric that attempts to measure the productivity and citation impact of a person's publications The h-index is an author-level metric that measures both the productivity and citation i

en.wikipedia.org

 

 

 

 

 

반응형

'Stack > Coding test' 카테고리의 다른 글

[C++ / Lv2] 전화번호 목록  (0) 2022.02.05
[C++ / Lv1] 완주하지 못한 선수  (0) 2022.02.04
[C++ / Lv2] 문자열 압축  (0) 2022.02.02
[C# / Lv2] 가장 큰 수  (0) 2022.01.18
[C# / Lv1] k번째 수  (0) 2022.01.17
반응형

 

 

 

 

풀이 코드

using System;

public class Solution {
    public string solution(int[] numbers) {
        string answer = GetAnswer(numbers);
        return answer;
    }

    private string GetAnswer(int[] numbers)
    {
        Array.Sort(numbers, (a, b) =>
                   {
                       string combineAB = string.Format("{0}{1}", a, b);
                       string combineBA = string.Format("{0}{1}", b, a);
                       return combineBA.CompareTo(combineAB);
                   });

        return (GetZeroCount(numbers) == numbers.Length) ? 
            "0" : string.Join("", numbers);
    }

    private int GetZeroCount(int[] sortedNumbers)
    {
        int returnVal = 0;
        for(int i = 0; i < sortedNumbers.Length; i++)
        {
            if(sortedNumbers[i] == 0)
            {
                returnVal++;
            }
        }

        return returnVal;
    }
}
  • 처음에는 문제에 나와있는대로 모든 경우의 수를 구하려다가 낭비가 너무 커지는것 같아서 포기했다.
  • 원소의 자릿수가 같으면 내림차순 정렬이 가장 큰 값을 가지지만 원소의 자릿수가 달라지면 오름차순의 수가 가장 큰 값을 가지게된다. (ex. [10, 9], [9, 10] ▶ "109" < "910"), (ex. [2, 1], [1, 2] ▶ "21" > "12")
  • 그래서 수로 정렬하지 않고, 두 원소의 값을 문자열로 합친 값을 비교하여 정렬함.
  • 정렬한 배열의 값이 0만 있을경우 "0"으로만 반환되게끔 예외 처리를 함.

 

 

 

기타 사용한 함수들

- string.CompareTo(string)

 

String.CompareTo 메서드 (System)

이 인스턴스를 지정된 개체 또는 String과 비교하고 정렬 순서에서 이 인스턴스의 위치가 지정된 개체 또는 String보다 앞인지, 뒤인지 또는 동일한지를 나타내는 정수를 반환합니다.Compares this insta

docs.microsoft.com

- string.Join(string, object[])

 

String.Join 메서드 (System)

각 요소 또는 멤버 사이에 지정된 구분 기호를 사용하여 지정된 배열 요소나 컬렉션 멤버를 연결합니다.Concatenates the elements of a specified array or the members of a collection, using the specified separator between e

docs.microsoft.com

 

반응형

'Stack > Coding test' 카테고리의 다른 글

[C++ / Lv2] 전화번호 목록  (0) 2022.02.05
[C++ / Lv1] 완주하지 못한 선수  (0) 2022.02.04
[C++ / Lv2] 문자열 압축  (0) 2022.02.02
[C# / Lv2] H-Index  (0) 2022.01.19
[C# / Lv1] k번째 수  (0) 2022.01.17
반응형

 

 

 

using System;

public class Solution {
    public int[] solution(int[] array, int[,] commands) {
        int[] answer = new int[commands.GetLength(0)];
        for(int i = 0; i < answer.Length; i++)
        {
            int start = commands[i, 0];
            int end = commands[i, 1];
            int[] splitArr = SplitArray(array, start, end);
            Array.Sort(splitArr);
            answer[i] = splitArr[commands[i, 2] - 1];
        }
        return answer;
    }
    
    private int[] SplitArray(int[] arr, int start, int end)
    {
        int[] returnArr = new int[end - start + 1];
        Array.Copy(arr, start - 1, returnArr, 0, returnArr.Length);
        return returnArr;
    }
}

 

 

이차원 배열

- 2차원 배열은 [행, 열]로 이루어져있다.

- 각 차원에 대한 길이(Length)는 GetLength(N)으로 가져올 수 있는데 N의 값은 행(0), 열(1)이다.

 

 

 

배열의 복사

- Array.Copy(sourceArray(A), startIndex(B), destArray(C), copyStartIndex(D), copyLength(E))

- 원본 배열(A)의 인덱스(B)부터 원하는 갯수(E)만큼의 배열값을 복사될 배열(C)의 인덱스(D)부터 복사를 진행한다.

- 여기서 (E)의 값은 인덱스값이 아니라 원소의 갯수를 의미한다. 즉 (D)와 (E)의 값이 destArray의 범위를 벗어나면 안된다. (복사될 원소의 갯수가 배열의 범위를 벗어나므로 에러 발생)

 

 

 

배열 정렬

- 기본적으로 오름차순으로 정렬되게 되어있다.

- 내림차순으로 정렬을 하려면 Sort한 뒤 Reverse함수를 호출해주거나 IComparer를 지정해서 내림차순 정렬이 가능하다.

using System;

public class ReverseComparer : IComparer
{
    public int Compare(object x, object y)
    {
        return (new CaseInsensitiveComparer()).Compare(y, x);
    }
}

void main()
{
    int[] arr = new int[] { 3, 7, 43, 7, 32, 5, 9, 11, 4, 2 };
    
    //case 1
    Array.Sort(arr);
    Array.Reverse(arr);
    
    //case 2
    IComparer revCompare = new ReverseComparer();
    Array.Sort(arr, revCompare);
    
    //case 3
    Array.Sort(arr, (a, b) =>
    {
        return b.CompareTo(a);
    });
}

 

 

 

 

 

 

반응형

'Stack > Coding test' 카테고리의 다른 글

[C++ / Lv2] 전화번호 목록  (0) 2022.02.05
[C++ / Lv1] 완주하지 못한 선수  (0) 2022.02.04
[C++ / Lv2] 문자열 압축  (0) 2022.02.02
[C# / Lv2] H-Index  (0) 2022.01.19
[C# / Lv2] 가장 큰 수  (0) 2022.01.18

+ Recent posts