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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
C
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int num[], int len, int target) {
int *answer = malloc(sizeof(int)*2);
answer[0]=answer[1]=0;
int star=0;
int i;
for(i=0;i<len;i++)
for(star=i;star<len-1;star++)
{
if(num[i]+num[star+i] == target)
{
answer[0]=i;
answer[1]=star+i;
break;
}
}
return answer;
}
结果
Your input
[3,2,4]
6
Your answer
[1,2]
Expected answer
[1,2]
c的思想:
类似:
num[0] + num[1]……num[len-1]
num[1] + num[2]…..num[len-1]
.
.
num[len-2] +num[len-1]
金字塔遍历, 一旦找到符合条件值,返回跳出遍历。
python3
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d={}
for i in range(len(nums)):
if nums[i] not in d:
d[target -nums[i]]=i
else:
return d[nums[i]],i
答案:
Your input
[3,2,4]
6
Your answer
[1,2]
注意在python中字典中,in 找的是字典的键,而不是字典的值,一个键对应一个值。
python的思路:
①遍历整个数组
②将数组[i]的值和目标值相减,得到的减数变为字典d{}中的键,该键在字典中所对应的数值是原来数组中的序列
③当数组中的值等于字典中的某个键时,表示数组中有数据相加等于目标值,返回字典中键所对应的值,和数组中值所对应的序列