1. Two Sum - 两数求和

https://leetcode.com/problems/two-sum/

分析

从数组中找出两个能相加等于指定值的组合,肯定可以采用一些比较高级的算法,循环遍历是最简单粗暴的。。。

实现

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

    return pArray;
}

猜你喜欢

转载自blog.csdn.net/qq_25077833/article/details/54918903