상세 컨텐츠

본문 제목

마지막 두 원소

코딩테스트/C#

by MJ_119 2024. 6. 10. 21:46

본문

 

문제 설명

정수 리스트 num_list가 주어질 때, 마지막 원소가 그전 원소보다 크면 마지막 원소에서 그전 원소를 뺀 값을 마지막 원소가 그전 원소보다 크지 않다면 마지막 원소를 두 배한 값을 추가하여 return하도록 solution 함수를 완성해주세요.


제한사항
  • 2 ≤ num_list의 길이 ≤ 10
  • 1 ≤ num_list의 원소 ≤ 9

입출력 예

 

 

using System;

public class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = new int[] {};
        
        answer = num_list;
        
        int a = 0;
        
        Array.Resize(ref answer, answer.Length + 1); // 배열 크기 1 증가
        
        if(num_list[num_list.Length -1] > num_list[num_list.Length-2])
        {
            a = num_list[num_list.Length-1] - num_list[num_list.Length-2];
            answer[answer.Length -1] = a;
        }
        else
        {
            a = num_list[num_list.Length-1] * 2;
            answer[answer.Length -1] = a;
        }
        
        return answer;
    }
}

 

다른 풀이

 

using System;

public class Solution {
    public int[] solution(int[] num_list) {
        int l = num_list.Length - 1;
        int a = num_list[l] > num_list[l-1] ? num_list[l]-num_list[l-1] : num_list[l]*2 ;
        Array.Resize(ref num_list, l+2);
        num_list[l+1] = a;
        return num_list;
    }
}

 

using System;

public class Solution {
    public int[] solution(int[] num_list) 
    {
        int[] answer = new int[num_list.Length + 1];
        Array.Copy(num_list, answer, num_list.Length);
        int a = num_list[num_list.Length - 2];
        int b = num_list[num_list.Length - 1];
        answer[answer.Length - 1] = b > a ? b - a : b * 2;
        return answer;
    }
}

 

using System;
using System.Collections.Generic;
public class Solution {
    public int[] solution(int[] num_list) {
        List<int> answer = new List<int>(num_list);
        if(num_list[num_list.Length-1] >num_list[num_list.Length-2]) 
            answer.Add(num_list[num_list.Length-1] -num_list[num_list.Length-2]);
        else
            answer.Add(num_list[num_list.Length-1] *2);
        return answer.ToArray();
    }
}

'코딩테스트 > C#' 카테고리의 다른 글

수 조작하기 2  (1) 2024.06.10
수 조작하기 1  (0) 2024.06.10
이어 붙인 수  (0) 2024.06.10
원소들의 곱과 합  (0) 2024.06.10
주사위 게임 2  (0) 2024.06.10

관련글 더보기