[코테 풀이] Distribute Elements Into Two Arrays I

시내·2024년 7월 15일
0

Q_3069) Distribute Elements Into Two Arrays I

출처 : https://leetcode.com/problems/distribute-elements-into-two-arrays-i/

You are given a 1-indexed array of distinct integers nums of length n.

You need to distribute all the elements of nums between two arrays arr1 and arr2 using n operations. In the first operation, append nums[1] to arr1. In the second operation, append nums[2] to arr2. Afterwards, in the ith operation:

  • If the last element of arr1 is greater than the last element of arr2, append nums[i] to arr1. Otherwise, append nums[i] to arr2.

The array result is formed by concatenating the arrays arr1 and arr2. For example, if arr1 == [1,2,3] and arr2 == [4,5,6], then result = [1,2,3,4,5,6].

Return the array result.

class Solution {
    public int[] resultArray(int[] nums) {
        int[] res = new int[nums.length];
        List<Integer> one = new ArrayList<>(), two = new ArrayList<>();
        one.add(nums[0]);
        two.add(nums[1]);
        for (int i = 2; i < nums.length; i++) {
            if (one.get(one.size() - 1) > two.get(two.size() - 1)) {
                one.add(nums[i]);
            } else two.add(nums[i]);
        }
        int ind = 0;
        for (int a : one) res[ind++] = a;
        for (int b : two) res[ind++] = b;
        return res;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글