Are you willing to challenge a very simple algorithm question?

Source: Internet
Author: User

Are you willing to challenge a very simple algorithm question?

Returns the sum of two numbers. This is simple enough! It is definitely not a problem to be able to do it. The question is whether you can do better. Okay. Please refer to the following questions:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution.
Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
After reading the question, do you already have an answer. It's easy to use the brute force method. It can be done in a dual loop. But is there any better way?
If you have already thought of it, there is no need to read it down.
If you have no clue, you may think about HashTable. It is actually quite simple, but sometimes it is impossible to think about the wrong direction. If you haven't thought of it yet, let's take a look!
After reading the question, do you already have an answer. It's easy to use the brute force method. It can be done in a dual loop. But is there any better way?
If you have already thought of it, there is no need to read it down.
Compared with a dual loop, the time efficiency may not be very good. For a long time, we can easily think of the "space for Time" that we often hear. In this way, we can use a dictionary key-value pair to save the Intermediate Value, reduce the cycle, and change it to a single loop, the time efficiency can be improved. So what exactly does this dictionary save? Save the target value minus the integer (key) of the current array and the subscript (value) of the integer of the array ). When we execute a loop, each loop goes to an integer in an array, we determine whether the integer is a key in the dictionary. If it is not, we store it in the dictionary according to the previous key value, if there is only one number that meets the requirements, you do not need to repeat the key. If yes, we can find the two integers, and then return the subscript of the two integers. The subscript of the first integer is the value corresponding to the current dictionary key, and the subscript of the second integer is the I value of the current loop. That's easy! If I am not clear enough, read the code directly.
The following is the implementation of C:
 1  using System; 2  using System.Collections.Generic; 3    4   namespace XiaoLiang 5   { 6       public class TwoSum 7       { 8           public int[] TwoSum(int[] nums, int target) 9          {10                  int[] result = new int[2];11                  Dictionary<int, int> dictionary = new Dictionary<int, int>();12          for (int i = 0; i < nums.Length; i ++ )13         {14                      if(dictionary.ContainsKey(nums[i]))15                      {16                          result[0] = dictionary[nums[i]];17                          result[1] = i;18                          return result;19                       }20                     else21                    {22                          dictionary.Add(target - nums[i] , i);23                    }24              }25              return result;26    }27   }28                                                  

 

The following is the implementation of C ++:
 1 class Solution { 2  public: 3       vector<int> twoSum(vector<int>& nums, int target) { 4           int i = 0, n = nums.size(); 5           unordered_map<int, int> m; 6           vector<int> ret; 7    8           for (i = 0; i < n; ++i) 9      {10              if (m.find(target - nums[i]) != m.end())11       {12                  ret.push_back(m[target - nums[i]]);13        ret.push_back(i);14                  break;15       }16              m[nums[i]] = i;17     }18  19          return ret;20   }21  };

 

 

If there is something wrong, you are welcome to make a brick. There are better ways to share it.

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.