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].



 1 /**
 2  * Note: The returned array must be malloced, assume caller calls free().
 3  */
 4 int* twoSum(int* nums, int numsSize, int target) {
 5     int *result = (int*)malloc(2 * sizeof(int));
 6     
 7     for(int i = 0; i < numsSize-1; i++){
 8         for(int j = i+1; j < numsSize; j++){
 9             if((nums[i] + nums[j]) == target){
10                 result[0] = i;
11                 result[1] = j;
12             }
13         }
14     }
15     return result;
16     
17 }

注意使用malloc为指针申请空间

 

 1 class Solution(object):
 2     def twoSum(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: List[int]
 7         """
 8         map= {}
 9         for i,n in enumerate(nums):
10             if map.has_key(n):
11                 return map[n],i
12             else:
13                 map[target - n] = i

map为字典

enumerate是枚举法,i 为索引,n为内容

map.has_key()判断字典中是否存在某键

map[n]将键n的值设为**

转载于:https://www.cnblogs.com/fullest-life/p/6475927.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值