刷题算法 1. Two Sum

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{}中的键,该键在字典中所对应的数值是原来数组中的序列
③当数组中的值等于字典中的某个键时,表示数组中有数据相加等于目标值,返回字典中键所对应的值,和数组中值所对应的序列

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值