返回動態分配的 int* 指向長度為 2 的數組,調用者負責 free。索引從 1 開始。
int* twoSum(int* nums, int numsSize, int target) {
for (int i = 0; i < numsSize; ++i) {
for (int j = i + 1; j < numsSize; ++j) {
if (nums[i] + nums[j] == target) {
int *res = malloc(sizeof(int) * 2);
res[0] = i + 1; // 1-based
res[1] = j + 1;
return res;
}
}
}
return NULL; // 題目保證有解
}C 標準庫無內建哈希表,可引入 uthash 或自寫簡單開放寻址表。面試中雙重循環通常可接受(numsSize ≤ 10⁴)。
malloc 分配返回數組,棧上數組函數返回後失效。free(res) 避免洩漏。