給你兩個整數數組 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
通過次數4,087提交次數4,983
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/create-target-array-in-the-given-order
解題思路:
當一個數組創建出來之後所有位置均爲0,當一個目標值不爲0時則將其目標位置後面的所有元素都向後移動一個位置,然後將目標值插入指定位置就行了。如果爲0直接插入元素就好。開始沒有看到提示上說所有元素 >0 所以考慮了負數的情況。
class Solution {
public int[] createTargetArray(int[] nums, int[] index) {
int[] target = new int[nums.length];
for ( int i = 0; i < nums.length;i++){
if (target[index[i]] != 0) {
target = this.move(target,index[i],nums[i]);
} else {
target[index[i]] = nums[i];
}
}
return target;
}
private int[] move(int[] array,int index,int value) {
int num = index;
while(array[++index] > 0);
while(index > num) {
array[index--] = array[index];
}
array[num] = value;
return array;
}
}
執行用時:1ms 內存消耗:38.5 MB
很僥倖的在用時和消耗都幹掉了100%的人,可能是大佬們都沒空看這麼簡單的題,不過我也沒有特意找簡單題去看,而是從推送消息最新那條周賽裏選的。