문제 설명
정수 리스트 num_list가 주어질 때, 마지막 원소가 그전 원소보다 크면 마지막 원소에서 그전 원소를 뺀 값을 마지막 원소가 그전 원소보다 크지 않다면 마지막 원소를 두 배한 값을 추가하여 return하도록 solution 함수를 완성해주세요.
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();
}
}