我的解法:
C:
/**
* Note: The returned array must be malloced, assume caller calls free().
首先搞清楚函数中的形参的意思:
int* nums表示传进去一个数组的地址;
int numsSize表示传进去的数组大小;
int target表示数组中两数相加需要等于的值;
int* returnSize表示返回的数组的大小。
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize)
{
int *a = (int*)malloc(sizeof(int)*2);
for(int i = 0; i <= numsSize-2; ++i) {
for(int j = i+1; j <= numsSize-1; ++j) {
if(nums[i]+nums[j] == target) {
a[0] = i;
a[1] = j;
*returnSize = 2;
return a;
}
}
}
*returnSize = 0;
return 0;
}
Python
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
for i in range(n): #长度
for j in range(i + 1, n):
if nums[i] + nums[j] == target:
return [i, j]
return []