[Solution]1389. Create Target Array in the Given Order

·

1 min read

Problem

Problem_Link

Solutions (time, space)

O(n^2), O(n)

class Solution {
    public int[] createTargetArray(int[] nums, int[] index) {
        List<Integer> temp = new ArrayList<Integer>();
        int[] target = new int[nums.length];

        for(int i=0;i<nums.length;i++) temp.add(index[i],nums[i]);

    //higher than java 8
        target = temp.stream().mapToInt(Integer::intValue).toArray();

    //lower than java 8
        //for(int i=0;i<nums.length;i++) target[i] = temp.get(i);

        return target;
    }
}

Explanation

  • put values in arraylist as index then convert to int array from arraylist.
  • in worst case, it is O(n^2).
  • There is another way, pair index and value then merge sort.O(n log n)
  • If problem must not reach O(n^2), should use merge sort.