LeetCode刷题:1389.按给定顺序创建目标数组. Create Target Array in the Given Order

LeetCode刷题:1389.按给定顺序创建目标数组. Create Target Array in the Given Order

给定两个整数数组 nums和index。您的任务是根据以下规则创建目标数组:

最初目标数组为空。
从左到右读NUMS [i]和指数[I],插入在指数index[i] 的值nums[i] 在 目标阵列。
重复上述步骤,直到没有元素在阅读nums和index.
返回目标数组。

保证插入操作将是有效的。

范例1:

输入: nums = [0,1,2,3,4],索引= [0,1,2,2,1]
输出: [0,4,1,3,2]
说明:
nums索引目标
0 0 [ 0]
1 1 [0,1]
2 2 [0,1,2]
3 2 [0,1,3,2]
4 1 [0,4,1,3,2]
范例2:

输入: nums = [1,2,3,4,0],索引= [0,1,2,3,0]
输出: [0,1,2,3,4]
说明:
nums索引目标
1 0 [ 1]
2 1 [1,2]
3 2 [1,2,3]
4 3 [1,2,3,4]
0 0 [0,1,2,3,4]
范例3:

输入: nums = [1],索引= [0]
输出: [1]

限制条件:

1 <= nums.length, index.length <= 100
nums.length == index.length
0 <= nums[i] <= 100
0 <= index[i] <= i

class Solution {
    public int[] createTargetArray(int[] nums, int[] index) {
        List<Integer> list = new ArrayList<>();
        int[] res = new int[nums.length];
        for(int i=0;i<nums.length;i++){
           if(i>index.length){
               break;
           }
            list.add(index[i],nums[i]);
            //往list集合里插入值,nums是值,index是下标索引
            //插入后原本索引右往移动一位
        }
        for(int j=0;j<list.size();j++){
            res[j]=list.get(j);
            //get方法将list的值赋给res数组
        }
            return res;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值