[Leetcode] The Sum of

Source: Internet
Author: User

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

The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.

You may assume this each input would has exactly one solution.

Input:Numbers={2, 7, one, A, target=9
Output:Index1=1, index2=2
began to write an O (n^2) solution, timed out. An O (n) solution was seen on the internet, using a hash map. Only iterate through the array, the number of traversed by the existence of a hash map, the value as the key, the ordinal I as value, so that you can achieve a fast lookup of the traversed value. For example, the current traversal to the K element, and then go to hash map to find Target-nums[k] This key exists, if there is printing two coordinates, if there is no current key-value to the hash map, of course, the premise of saving is that this value is the first occurrence, If you've already seen it before, skip to the next element without saving it. In C + +, of course, the map is implemented, but the map in C + + is implemented by default, with an average lookup complexity of O (Logn). The last time complexity is O (NLOGN)


Class Solution {public:     vector<int> twosum (vector<int>& nums, int target) {          std::vector< int> result;          if (nums.size () = = 0) return result;          int index1 = 0, index2 = 0;          Map<int, Int> appeared;          for (int i = 0; i < nums.size (); i++) {               if (Appeared.count (Target-nums[i])) {                    Result.push_back (appeared[target -Nums[i]] + 1);                    Result.push_back (i + 1);                    return result;               }               if (!appeared.count (Nums[i]))                    appeared[nums[i]] = i;          }}               ;



[Leetcode] The Sum of

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.