[Leetcode 001] Two sum

Source: Internet
Author: User
Question:

Given an array of integers, returnIndicesOf the two numbers such that they add up to a specific target.

You may assume that each input wocould haveExactlyOne solution.

Example:

Given Nums = [2, 7, 11, 15], target = 9,
Because Nums [0] + Nums [1] = 2 + 7 = 9,
Return [0, 1].

Method:

Java

  • 1. Dual-cycle of violence, time complexity is O (n ^ 2)
  1. publicclassSolution{
  2. publicint[] twoSum(int[] nums,int target){
  3. int[] arr =newint[2];
  4. for(int i =0;i< nums.length-1; i++){
  5. for(int j = i+1; j< nums.length; j++){
  6. if(target == nums[i]+ nums[j]){
  7. arr[0]= i ;
  8. arr[1]= j ;
  9. }
  10. }
  11. }
  12. return arr ;
  13. }
  14. }
  • 2. With hashmap or hashtable, the time complexity is O (n)
  1. publicclassSolution{
  2. publicint[] twoSum(int[] nums,int target){
  3. int[] result ={0,0};
  4. Map<Integer,Integer> map =newHashMap<Integer,Integer>();
  5. for(int i =0;i<nums.length;i++){
  6. if(map.containsKey(target-nums[i])){
  7. result[0]= map.get(target-nums[i]);
  8. result[1]= i;
  9. }else{
  10. map.put(nums[i],i);
  11. }
  12. }
  13. return result ;
  14. }
  15. }

Analysis of ideas:
Obviously better than the first solution, greatly reducing the time complexity
Create a hash table and use the array's V value and index value as the K-V of the hash table
When target-K exists in the table, the corresponding value is taken out, which is the location to be searched.

Python
The same hashtable idea, key is number, value is Index

  1. classSolution(object):
  2. def twoSum(self, nums, target):
  3. """
  4. :type nums: List[int]
  5. :type target: int
  6. :rtype: List[int]
  7. """
  8. index ={};
  9. for i,j in enumerate(nums):
  10. if target-j in index:
  11. return[index[target-j],i]
  12. index[j]= i



From Weizhi note (wiz)



[Leetcode 001] Two sum

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.