1. Both Sum "array | hash table"

Source: Internet
Author: User

Given an array of integers, return indices of the both numbers such that they add-to a specific target.

You may assume this each input would has exactly one solution.

Version 1:o (n^2) "Violent original Version" 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]
Version 2:O (n^2) "Brute Force enumeration function enhancement"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]
Version 3:o (n)"Two-way 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]]
Version 4: O (n)"One way 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. }
The use of 1.enumerate built-in functions (enumeration functions)---Used to traverse the index and iterate through the elements; You can receive the second parameter to specify the index starting value.

1. Both Sum "array | hash table"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.