1. The Sum of the
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.
Example:
Given nums = [2, 7, one, 2], target = 9,because nums[0] + nums[1] = + 7 = 9,return [0, 1].
Main topic:
Finds the sum of 2 elements in an array and equals the number of targets, outputting the subscripts of these two elements.
Ideas:
The stupidest way to deal with it is to double-cycle it. Time complexity O (n*n).
The code is as follows:
Class solution {public: vector<int> twosum (vector<int>& nums, int target) { vector<int> result; int i,j; for (I = 0; i < nums.size (); i++) { for (j = i+1; j < nums.size (); j + +) { if (nums [I] + nums[j] == target) { &nbsP; result.push_back (i); result.push_back (j); break; } } } return result; }};
Refer to the practices of others: Https://discuss.leetcode.com/topic/3294/accepted-c-o-n-solution
Using the key value of the map, the element is the key, the index of the element to do the value.
Vector<int> twosum (Vector<int> &numbers, int target) { //key is the number and value is its index in the vector. unordered_map<int, int> hash; vector<int> result; for (int i = 0; i < numbers.size (); i++) { int numbertofind = target - numbers[i]; //if numberToFind is found in map, return them if (Hash.find (Numbertofind) != hash.end ()) { result.push_back (Hash[numbertofind]); result.push_back (i ); return result; } //number was not found. put it in the map. hash[numbers[i]] = i; } return result;}
2016-08-11 15:02:14
This article is from the "Do Your best" blog, so be sure to keep this source http://qiaopeng688.blog.51cto.com/3572484/1836898
Leetcode 1. A Sum array of