Description

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.

Translation

整形数组中每个元素均不相同,且两两相加的结果也不相同。给定某一目标数字,返回数组中相加结果为给定目标数字的两个元素的下标。

Example

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

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

Solution

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */

Method1 (循环遍历)

对数组内的元素两两逐次相加,记录其下标。

int* twoSum(int* nums, int numsSize, int target) {
    int* arrIndices = (int*)malloc(sizeof(int) * 2);
    for(i = 0; i < numsSize - 1; i++){
        for(j = i + 1; j < numsSize; j++){
            if (nums[i] + nums[j] == target){
                flag[0] = i;
                flag[1] = j;
                break;
            }
            else
                continue;
        }
    }
    return arrIndices;
}

时间复杂度: O(n2)
空间复杂度: O(1)


Charles_wyt
2 声望0 粉丝

来啊,一起写Bug