给你两个整数数组 nums 和 index。你须要按照如下规则建立目标数组:html
请你返回目标数组。数组
题目保证数字插入位置老是存在。ide
示例 1:测试
输入:nums = [0,1,2,3,4], index = [0,1,2,2,1]url
输出:[0,4,1,3,2]spa
解释:.net
nums index targethtm
0 0 [0]blog
1 1 [0,1]element
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]
提示:
来源:力扣(LeetCode)
先初始化一个数组target,所有用-1填充,而后用下标i循环遍历数组index和nums。
若是target[index[i]]为-1,说明这个位置没有插入过数字,直接复制target[index[i]] = nums[i]便可。
若是target[index[i]]不为-1,说明这个位置已经插入过数字,那么须要要将targer数组的index..length这段元素依次日后移动一位,而后再设置target[index[i]] = nums[i]。
循环次数 nums index target
0 1 0 [1]
1 2 1 [1,2]
2 3 2 [1,2,3]
3 4 3 [1,2,3,4]
4 0 0 [0,1,2,3,4]
class Solution(object): def createTargetArray(self, nums, index): """ :type nums: List[int] :type index: List[int] :rtype: List[int] """ length = len(nums) #初始化目标target数组 target = [-1] * length #下标法遍历两个数组 for i in range(length): #若是target的下标为index[i]的位置没有插入过数字 if target[index[i]] == -1: #直接复制num[i]给target[index[i]] target[index[i]] = nums[i] else: #将下标为index[i]到length-1处的元素后移 for j in range(length-1, index[i], -1): target[j] = target[j-1] #后移完以后在复制target[index[i]] target[index[i]] = nums[i] return target
各位大神,有其余思路欢迎留言~
博主:测试生财
座右铭:专一测试与自动化,致力提升研发效能;经过测试精进完成原始积累,经过读书理财奔向财务自由。
csdn:https://blog.csdn.net/ccgshigao