[leetCode]Easy - Two Sum 解題紀錄

Champion Hsieh
Firmware_Engineer
Published in
1 min readJun 20, 2021

Two Sum / C語言 / 暴力法

Question:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

給一陣列nums跟一整數target,回傳兩數和為target整數的兩數索引值。

你可以假定每一個輸入都會有一個解題方法,且你不能使用相同元素兩次。

你可以以任何序列回傳答案。

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Solution:

/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){

int* temp = NULL;
for(int i=0;i<numsSize;i++){
for(int j=i+1;j<numsSize;j++){
if (target == nums[i]+nums[j]){
temp = malloc(sizeof(int) * 2);
temp[0] = i;
temp[1] = j;
printf("%d and %d\n", temp[0], temp[1]);
*returnSize = 2;
return temp;
}
}
}
return temp;
}

Note:

要自行配置記憶體,C 可以使用 malloc,它定義在 stdlib.h,舉例來說,可以在程式中以動態方式配置一個 int 型態大小的記憶體,例如:

int *p = malloc(sizeof(int));

在這段程式中,malloc 會配置一個 int 需要的空間,並傳回該空間的位址,可以使用指標 p 來儲存位址

想配置連續個指定型態的空間,可以如下:

int *p = malloc(sizeof(int) * 1000);

--

--