two sumtwo sum

每天一道在线编程题

问题:Two Sum

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.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解决方案:(C语言)
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

int result[2]={0,0};
int* twoSum(int* nums, int numsSize, int target) {

    int count=0;
    int remainder=0;
    int n=0;
    while(count < numsSize)
    {
        remainder=target-nums[count];
        n=count+1;
        while( n < numsSize)
        {
            if(remainder == nums[n])
            {
                 result[0]=count;
                 result[1]=n;
                 return result;
            }
            n++;
        }
        count++;
    }
    return result;
}

【注意】本文属于作者原创,欢迎转载!转载时请注明以下内容:

(转载自)ShengChangJian's Blog编程技术文章地址:

https://ShengChangJian.github.io/2016/06/two-sum.html


主页地址:http://shengchangjian.github.io/