Leetcode 每日刷题 --两数之和

Probelm:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

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

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9

Output: [0,1]

Result:

/**

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

*/

int* twoSum(int* nums, int numsSize, int target, int* returnSize){

int *result = NULL;

*returnSize = 0;

for (int i = 0; i < numsSize - 1; i++) {

for (int j = i + 1; j < numsSize; j++) {

if (nums[i] + nums[j] == target) {

result = malloc(2 * sizeof(int));

if (!result)

return NULL;

result[0] = i;

result[1] = j;

*returnSize = 2;

return result;

}

}

}

return NULL;

}

你可能感兴趣的:(Leetcode,leetcode,算法,职场和发展)