LeetCode 1. Two Sum ( C ) – Easy

題目為輸入一串數列,要尋找兩個數字相加與目標值相同的數,並回傳它們的位置。

原文題目如下

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.

Example 1:

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

下方為我使用 C 語言的解法

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    int yn = -1;
    *returnSize = 2;
    int *arr = malloc(*returnSize * sizeof(int));
    for(int i = 0;i<numsSize;i++){
        for(int j = 0;j<numsSize;j++){
            if(i!=j)
                if(nums[i]+nums[j]==target){
                    arr[0] = i;
                    arr[1] = j;
                    yn = 1;
                    break;
                }
        }
        if(yn==1)
            break;
    }
    if(yn == -1){
        *returnSize = 0;
        free(arr);
    }
    return arr;
}

下方為時間與空間之消耗

Runtime: 4 ms, faster than 94.34% of C online submissions for Two Sum.

Memory Usage: 5.8 MB, less than 99.72% of C online submissions for Two Sum.

下一題連結 : LeetCode 2. Add Two Numbers

Add a Comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *