LeetCode:1389. Create Target Array in the Given Order按既定順序建立目標陣列(C語言)
阿新 • • 發佈:2020-12-15
技術標籤:LeetCode
題目描述:
給你兩個整數陣列 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]
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
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/create-target-array-in-the-given-order
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
解答:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* createTargetArray(int* nums, int numsSize, int* index, int indexSize, int* returnSize){
int * res = (int*)malloc(sizeof(int) * indexSize);
int tail = -1;
int i = 0;
int j = 0;
for (i = 0; i < indexSize; i++) {
for(j=indexSize-1;j>index[i];j--){
res[j]=res[j-1];
}
res[index[i]] = nums[i];
}
*returnSize = indexSize;
return res;
}
執行結果: