1. 程式人生 > >LeetCode 之Two Sum(C)

LeetCode 之Two Sum(C)

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

給定一個整數陣列,返回兩個數字的索引,使它們相加到特定目標。

您可以假設每個輸入只有一個解決方案,並且您可能不會兩次使用相同的元素。

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

程式碼:

#include <stdio.h>
#include <stdlib.h>

int *twoSum(int* nums, int numsSize, int target)
{
    int tmp = 0;
    int ret = 0;
    int correspond = 0;
    int *res=NULL;
    res = malloc(2*sizeof(int));
    for(tmp = 0;tmp < numsSize;tmp++)
        {
            res[0] = tmp;
            correspond = target - *(nums+tmp);
                for(ret = tmp+1;ret < numsSize;ret++)    // tmp+1 防止同一資料複用
                    {
                        if(*(nums+ret) == correspond)
                            {
                                res[1] = ret;
                                return res;
                            }
                    }
        }

}

int main()
{
    int target = 9;
    int nums[]={2,7,11,15};
    int *ret=NULL;
    int numsSize=(sizeof(nums)/sizeof(nums[0]));
    ret = twoSum(nums,numsSize,target);
    printf("nums[%d] = %d.\n",*ret,nums[*ret]);
    printf("nums[%d] = %d.\n",*(ret+1),nums[*(ret+1)]);
    return 0;
}