본문 바로가기
Study with me/프로그래머스 L0 마스터하기

프로그래머스 - L0 마지막두원소 // Array ↔ List

by 외계나무 2023. 11. 30.

프로그래머스 - level 0 마지막 두 원소

class Solution {
    public int[] solution(int[] num_list) {
        int[] answer = new int[num_list.length + 1];
        int a = num_list[num_list.length-1];
        int b = num_list[num_list.length-2];
        int k = (a > b) ? a-b : a*2;
        System.arraycopy(num_list, 0, answer, 0, num_list.length);
        answer[answer.length-1] = k;
        return answer;
    }
}

 

System.arraycopy
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
public static void arraycopy(원본배열, 원본배열시작점, 복사할배열, 복사할시작점, 복사될요소수)
출처




타인의 풀이 1

import java.util.stream.IntStream;

class Solution {
    public int[] solution(int[] num_list) {
        return IntStream.iterate(0, i -> i + 1)
                        .limit(num_list.length + 1)
                        .map(i -> i == num_list.length ? (num_list[i - 1] > num_list[i - 2] ? num_list[i - 1] - num_list[i - 2] : 2 * num_list[i - 1]) : num_list[i])
                        .toArray();
    }
}

 

타인의 풀이 2

import java.util.*;
import java.util.stream.Collectors;

class Solution {
    public int[] solution(int[] num_list) {
        int lastFirst = num_list[num_list.length -1];
        int lastSecond = num_list[num_list.length -2];

        List<Integer> list = Arrays.stream(num_list).boxed().collect(Collectors.toList()); 


        list.add(lastFirst - lastSecond > 0 ? lastFirst - lastSecond : lastFirst * 2);

        return list.stream().mapToInt(Integer::intValue).toArray(); 
    }
}

 

List → Array

Type[] array = list.toArray(new Type[0]);
Type[] array = list.toArray(Type[]::new);  // Java 11 ~

 

Array → List

List<Type> list = Arrays.asList(array);