码迷,mamicode.com
首页 > 编程语言 > 详细

1. Two Sum【数组|哈希表】

时间:2017-03-27 00:30:34      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:margin   --   dice   name   index   rate   one   key   ble   

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.

 

版本1:O(n^2)  【暴力 原始版本】O(1)

  1. classSolution(object):
  2. def twoSum(self, nums, target):
  3. length = len(nums)
  4. for i in range(length):
  5. for j in range(i+1,length)://游标后移
  6. if nums[i]+ nums[j]== target:
  7. return[i,j]
版本2:O(n^2)  【暴力 枚举函数增强】O(1
  1. classSolution(object):
  2. def twoSum(self, nums, target):
  3. for index , item in enumerate(nums):
  4. for past_index , past_item in enumerate(nums[index+1:],index+1):
  5. if item + past_item == target:
  6. return[index, past_index]
版本3:O(n)    【双程hash table】O(n)
  1. classSolution(object):
  2. def twoSum(self, nums, target):
  3. dd = dict()
  4. for index , value in enumerate(nums):
  5. dd[value]= index
  6. for index , value in enumerate(nums):
  7. tt = target - value
  8. if dd.has_key(tt)and dd[tt]!= index:
  9. return[index , dd[tt]]
版本4:O(n)    【单程hash table】O(n)
技术分享
Python
  1. classSolution(object):
  2. def twoSum(self, nums, target):
  3. dd = dict()
  4. for index , value in enumerate(nums):
  5. tt = target - value
  6. if dd.has_key(tt)and dd[tt]!= index:
  7. return[dd[tt],index]
  8. else:
  9. dd[value]= index
Java
  1. public int[] twoSum(int[] nums, int target){
  2. Map<Integer,Integer> map = new HashMap<Integer,Integer>();
  3. for( int i=0;i<nums.length;i++){
  4. if(!map.containsKey(target - nums[i])){
  5. map.put(nums[i], i );
  6. }else{
  7. int[] rs ={ map.get(target-nums[i]), i };
  8. return rs;
  9. }
  10. }
  11. return nums;
  12. }
 
1.enumerate内置函数的使用(枚举函数)---用于既要遍历索引又要遍历元素;可以接收第二个参数用于指定索引起始值。

1. Two Sum【数组|哈希表】

标签:margin   --   dice   name   index   rate   one   key   ble   

原文地址:http://www.cnblogs.com/flyfatty/p/6624787.html

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