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;}};