給你兩個整數數組 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