LeetCode 1 Two Sum

Source: Internet
Author: User

LeetCode 1 Two Sum
Problem:

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

The function twoSum shocould return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input wowould have exactly one solution.

Input: numbers = {2, 7, 11, 15}, target = 9
Output: index1 = 1, index2 = 2

Solution:

O (n2) runtime, O (1) space-Brute force:

The brute force approach is simple. loop through each element x and find if there is another value that equals to target-x. as finding another value requires looping through the rest of array, its runtime complexity is O (n2 ).

O (n) runtime, O (n) space-Hash table:

We cocould reduce the runtime complexity of looking up a value to O (1) using a hash map that maps a value to its index.

Average Rating: 4.5 (874 votes)

Is this solution helpful? Read our book to learn more.

Question:

Given an array and a target integer, calculate the subscript of the two in the array and the target function. The first subscript must be smaller than the second subscript (ensure that there is only one result)

Solution:

Two Methods: brute-force cracking. Find a number and find the target in the array minus the number. The time complexity is O (n ^ 2), which is too inefficient. TLE

The second method is to solve the problem by using the Hash that can be frequently thought of (this method is used in this article ).

The other methods are the Binary Search Tree, the binary Balance Tree, and the B-tree, but there is no code implementation. I don't know if it is correct.

The following is the problem-solving code for C, C ++, Java, and Python.

Java source code:

Import java. util. *; public class Solution {public int [] twoSum (int [] nums, int target) {Map
 
  
Map = new HashMap
  
   
(); For (int I = 0; I
   
    
C language source code (C code has implemented Map itself, so the code is relatively long ):
    

# Include
     
      
# Include
      
       
# Define HASH_SIZE 10000 struct node {int value; int key; struct node * next;}; struct node * data [HASH_SIZE]; int contains (int key) {int hash = abs (key) % HASH_SIZE; struct node * p = data [hash]; while (p! = NULL) {if (p-> key = key) return 1; p = p-> next;} return 0;} void put (int key, int value) {int hash = abs (key) % HASH_SIZE; struct node * p = data [hash]; struct node * s = (struct node *) malloc (sizeof (struct node )); s-> key = key; s-> value = value; s-> next = NULL; if (p = NULL) {data [hash] = s; return ;} while (p-> next! = NULL) {p = p-> next;} p-> next = s;} int get (int key) {int hash = abs (key) % HASH_SIZE; struct node * p = data [hash]; while (p! = NULL) {if (p-> key = key) return p-> value; p = p-> next;} return 0;} int abs (int value) {return value> 0? Value:-value;} int * twoSum (int * nums, int numsSize, int target) {int * res = (int *) malloc (sizeof (int) * 2 ); int value; for (value = 0; value
       
        
C ++ source code (using STL map ):
        
#include
         
          #include
          
           #include
           using namespace std;class Solution {public:    vector
            
              twoSum(vector
             
              & nums, int target) {        map
              
                map; for(int i=0;i
               
                ::iterator iter; iter = map.find(target-nums[i]); if(iter!=map.end()){ vector
                
                  vec;vec.push_back(iter->second);vec.push_back(i+1);return vec; } map[nums[i]]=i+1; } return vector
                 
                  (); }};
                 
                
               
              
             
            
          
         
Python source code ):

class Solution:    # @param {integer[]} nums    # @param {integer} target    # @return {integer[]}    def twoSum(self, nums, target):        map={};        for i in range(0,len(nums)):            if map.has_key(target-nums[i]):                return map[target-nums[i]],i+1            map[nums[i]]=i+1        return 0,0



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.