Skip to content

3069. Distribute Elements Into Two Arrays I 👍

  • Time: O(n)O(n)
  • Space: O(n)O(n)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  vector<int> resultArray(vector<int>& nums) {
    vector<int> arr1{nums[0]};
    vector<int> arr2{nums[1]};

    for (int i = 2; i < nums.size(); i++)
      if (arr1.back() > arr2.back())
        arr1.push_back(nums[i]);
      else
        arr2.push_back(nums[i]);

    arr1.insert(arr1.end(), arr2.begin(), arr2.end());
    return arr1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int[] resultArray(int[] nums) {
    List<Integer> arr1 = new ArrayList<>(List.of(nums[0]));
    List<Integer> arr2 = new ArrayList<>(List.of(nums[1]));

    for (int i = 2; i < nums.length; ++i)
      if (arr1.get(arr1.size() - 1) > arr2.get(arr2.size() - 1))
        arr1.add(nums[i]);
      else
        arr2.add(nums[i]);

    arr1.addAll(arr2);
    return arr1.stream().mapToInt(Integer::intValue).toArray();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def resultArray(self, nums: list[int]) -> list[int]:
    arr1 = [nums[0]]
    arr2 = [nums[1]]

    for i in range(2, len(nums)):
      if arr1[-1] > arr2[-1]:
        arr1.append(nums[i])
      else:
        arr2.append(nums[i])

    return arr1 + arr2
Was this page helpful?