1. Two Sum数组|哈希表

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

 

版本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数组|哈希表的主要内容,如果未能解决你的问题,请参考以下文章

leetcode#1Two Sum

LeetCode 1. 两数之和 Two Sum (Easy)

1. 两数之和 [leetcode 1: Two Sum]

1. 两数之和 [leetcode 1: Two Sum]

[leetcode]599. Minimum Index Sum of Two Lists

LeetCode two sum -- scala 题解与思路