zoukankan      html  css  js  c++  java
  • LeetCode~5364. 按既定顺序创建目标数组

    给你两个整数数组 nums 和 index。你需要按照以下规则创建目标数组:

    目标数组 target 最初为空。
    按从左到右的顺序依次读取 nums[i] 和 index[i],在 target 数组中的下标 index[i] 处插入值 nums[i] 。
    重复上一步,直到在 nums 和 index 中都没有要读取的元素。
    请你返回目标数组。

    题目保证数字插入位置总是存在。

    示例:

    示例 1:
    输入:nums = [0,1,2,3,4], index = [0,1,2,2,1]
    输出:[0,4,1,3,2]
    解释:
    nums       index     target
    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], index = [0,1,2,3,0]
    输出:[0,1,2,3,4]
    解释:
    nums       index     target
    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], index = [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) {
            // 判空处理
            if(nums == null || nums.length == 0){
                return nums;
            }
    		// 初始化返回数组,并赋值为-1
            int[] target = new int[nums.length];
            Arrays.fill(target, -1);
            int i = 0, j = i;
    		// 遍历数组,在target下标index[i]处插入nums[i] (是插入,别写成替换了)
            for(; i < target.length; i++){
                // 判断是否为-1(未使用的位置),如果该位置已被使用,则需依次后移一位
                if(target[index[i]] != -1){
                    // 从后往前判断,依次将所插入元素后移一位,腾出位置给当前元素插入
                    for(j = nums.length; j > index[i]; j--){
                        if(target[j - 1] != -1){
                            target[j] = target[j - 1];
                        }
                    }
                }
                // 插入元素
                target[index[i]] = nums[i];
            }
            // 返回结果
            return target;
        }
    }
    

    提交结果

    5364.按既定顺序创建目标数组.png

    来源:力扣(LeetCode)
    链接: https://leetcode-cn.com/problems/create-target-array-in-the-given-order/submissions/

  • 相关阅读:
    康师傅JVM:运行时数据区概述及线程(三)
    康师傅JVM:程序计数器(四)
    Git常用命令
    Arthas概述
    康师傅JVM:JVM与Java体系结构(一)
    LabVIEW 连接MySQL数据库
    LabVIEW dll 崩溃
    LabVIEW 关于定时的研究
    NI 配置管理软件MAX的一些功能使用介绍
    LabVIEW 串口通信
  • 原文地址:https://www.cnblogs.com/unrecognized/p/12566628.html
Copyright © 2011-2022 走看看