前幾篇我們學了指標存取(1295 題)、以及用 malloc 建立新陣列(977 題)
今天要挑一個更直覺的題目 —— 在一個新陣列中「插入元素」,這正好能再一次鞏固 malloc 與指標操作。
題目介紹
leetcode1389. Create Target Array in the Given Order
給兩個陣列 nums 和 index,請依照 index[i] 的位置,把 nums[i] 插入到目標陣列中。
解題思路
這題我們要根據 index 陣列,把 nums 的元素依序插入到新陣列 target。前幾天我們練過陣列複製、拼接,今天進一步用到指標與記憶體搬移。
做法:
先用 malloc 配出一個大小為 n 的陣列 target,並準備 currentSize=0
對於每個 i:取 pos = index[i],val = nums[i]
如果 pos < currentSize,就要把 target[pos..currentSize-1] 整段往右搬一格。這裡可以用 memmove,一次處理好搬移
把 val 放進 target[pos],然後 currentSize++
最後回傳 target,並設 *returnSize = n\
這裡的關鍵在於:
指標操作:memmove(&target[pos+1], &target[pos], (currentSize - pos) * sizeof(int));
避免 off-by-one:檢查邊界情況(在尾端插入就不用搬移)。