【Leetcode】1. Two Sum

传送门

【题意】:从给定的一组数中找到两个数的和为target.返回两个数的序号,假设每次输入只有一组解

代码1:

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int> &numbers, int target) {
 4     int n = numbers.size();
 5     vector<int> result;
 6     for(int i = 0; i < n - 1; i++)
 7     {
 8         for(int j = i + 1; j < n; j++)
 9         {
10             if(numbers[i] + numbers[j] == target)
11             {
12                 result.push_back(i);
13                 result.push_back(j);
14                 return result;
15             }
16         }
17     }
18 }
19 };

 代码2:

 1 vector<int> twoSum(vector<int> &numbers, int target)
 2 {
 3     //Key is the number and value is its index in the vector.
 4     unordered_map<int, int> hash;
 5     vector<int> result;
 6     for (int i = 0; i < numbers.size(); i++) {
 7         int numberToFind = target - numbers[i];
 8 
 9             //if numberToFind is found in map, return them
10         if (hash.find(numberToFind) != hash.end()) {
11                     //+1 because indices are NOT zero based
12             result.push_back(hash[numberToFind] + 1);
13             result.push_back(i + 1);            
14             return result;
15         }
16 
17             //number was not found. Put it in the map.
18         hash[numbers[i]] = i;
19     }
20     return result;
class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
    int n = numbers.size();
    vector<int> result;
    for(int i = 0; i < n - 1; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
            if(numbers[i] + numbers[j] == target)
            {
                result.push_back(i);
                result.push_back(j);
                return result;
            }
        }
    }
}
};

  

原文地址:https://www.cnblogs.com/sunbines/p/9046682.html