本文共 1282 字,大约阅读时间需要 4 分钟。
要解决这个问题,我们需要创建一个目标数组 target,根据给定的 nums 和 index 数组中的元素进行插入操作。具体来说,我们需要按照顺序依次读取 nums[i] 和 index[i],并在 target 数组中的 index[i] 处插入 nums[i]。在插入时,如果目标位置已经被占用,需要将后续元素依次后移以腾出位置。
nums 长度相同的数组 target,初始值为 -1。nums 和 index 数组中的每个元素。这种方法确保了每个元素都能正确插入到指定的位置,同时保持插入顺序。
import java.util.Arrays;public class Solution { public int[] createTargetArray(int[] nums, int[] index) { int[] target = new int[nums.length]; Arrays.fill(target, -1); int i = 0; while (i < nums.length) { int currentIndex = index[i]; if (target[currentIndex] != -1) { for (int j = nums.length - 1; j > currentIndex; j--) { if (target[j - 1] != -1) { target[j] = target[j - 1]; } } } target[currentIndex] = nums[i]; i++; } return target; }} Arrays.fill 初始化 target 数组为 -1。while 循环遍历 nums 和 index 数组的元素。target 数组中的 index[i] 是否为 -1。如果不是,进入一个从末尾开始遍历的循环,找到第一个可用的位置并进行后移调整。这种方法确保了插入顺序的正确性,并且在处理过程中尽量减少了不必要的遍历,提高了效率。
转载地址:http://arnl.baihongyu.com/