码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode #1 Two Sum

时间:2017-06-27 21:17:08      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:个数   下标   说明   key   put   tar   复杂   结构体   value   

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.最简单粗暴的肯定就是进行两层循环,以第一个数为基准遍历剩余的数判断是否和另一个数相加为指定和。复杂度为O(n^2)

2.觉得这样的做法比较粗暴,效率不高,后来就考虑先将数排一遍序,初始两个下标i、j,默认j在i后面,i从第一个数(下标为0)开始,j往后加,判断相加符不符合,如果发现大了,说明后面的数肯定也不行了(毕竟已经排过序了),这时就让j下标回退一步,让i下标增加尝试匹配。比如说1+6!=9、1+9!=9,但是3+6=9,如果j下标不回退有可能会错过匹配。但是以上办法有一个需要注意的地方,就是普通排序后会下标错位,所以你要考虑如何保存下标,可以考虑用一个结构体把数和下标一起保存进行排序;

3.考虑了以上种种问题后,使用map这种key-value的方式进行存储,Python中对应的是dict,思路就是一个个判断下来,假设当前数为a,以target-a作为key去dict中取数,取到则说明能匹配,返回value和当前下标,如果不存在则更新,把值a作为key存入当前下标,这样读到a时就可以用target-a判断有没有存在该匹配了。

 

参考代码:

 1 class Solution:
 2     def twoSum(self, nums, target):
 3         """
 4         :type nums: List[int]
 5         :type target: int
 6         :rtype: List[int]
 7         """
 8         lens = len(nums)
 9         i = 0
10         map_item = {}
11         while i < lens:
12             if map_item.get(nums[i]) is not None  :
13                 return [nums.index(target-nums[i]),i]
14             else:
15                 map_item[target-nums[i]]=nums[i]
16             i = i + 1

 

LeetCode #1 Two Sum

标签:个数   下标   说明   key   put   tar   复杂   结构体   value   

原文地址:http://www.cnblogs.com/lhppom/p/7087147.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!