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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章