Leetcode --------------- Two Sum

Source: Internet
Author: User

Leetcode --------------- Two Sum

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

Given an array, give a number target, find the sum of two numbers in the array, and find the positions of these two numbers. Its subscript index starts from 1.

Ideas:

Method 1: profiteering, two for loop traversal, locate exit, complexity O (n2)

Method 2: hash uses a hash table to store the subscript corresponding to each number. The complexity is O (n ).

Solution 2:

 

class Solution {public:vector
 
   twoSum(vector
  
    &numbers, int target) {unordered_map
   
     mapping;vector
    
      result;for (int i = 0; i < numbers.size(); ++i){mapping[numbers[i]] = i;}for (int i = 0; i < numbers.size(); ++i){const int tmp = target - numbers[i];if (mapping.find(tmp) != mapping.end() && mapping[tmp]>i){result.push_back(i+1);result.push_back(mapping[tmp] + 1);break;}}return result;}};
    
   
  
 
The online push result is:

 


Question:
Similar to Question [1. Two Sum], doesn't that the input array is already sorted in
Ascending order.

Problem: If the array is ordered, we can traverse from the beginning and end to the center at the same time.

 

class Solution{public:vector
 
   twoSum(vector
  
    &numbers, int target){vector
   
     result;int i = 0;int j = numbers.size() - 1;while (i < j){int sum = numbers[i] + numbers[j];if (sum < target)++i;else if (sum>target)--j;else{result.push_back(i + 1);result.push_back(j + 1);break;}}return result;}};
   
  
 


 

 

 

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.