#1 Two Sum

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

The function twoSum should 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 would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

解法1:暴力寻找,可以通过(网上说不可以,不知道为什么我的就可以)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        //给定一个数组,求两个和等于目标值的下标,下标从1开始
        int sum = 0;
        vector<int> index;
        int length = nums.size();
        for(int i = 0; i < length; i++) {
            for(int j = length - 1; j > i; j--) {
                sum = nums[i] + nums[j];
                if(sum == target) {
                    index.insert(index.begin(), j + 1);
                    index.insert(index.begin(), i + 1);
                  break;  
                }
                else continue;
            }
        }
        return index;
          
    }
};

解法2:哈希表

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        //给定一个数组,求两个和等于目标值的下标,下标从1开始
        map<int, int> hash;
        vector<int> out(2);
        //赋值存入哈希表,建立映射关系,位置和键值对应 
        for(int i = 0; i < nums.size(); i++) {
            hash[nums[i]] = i;
        }
        for(int i = 0; i < nums.size(); i++) {
            //找到目标值的位置,且不等于本身的位置
            if(hash.find(target - nums[i]) != hash.end() && hash[target - nums[i]] != i) {
            out[0] = i + 1;
            out[1] = hash[target - nums[i]] + 1;
            break;    
            }
        }
        return out; 
    }
};

  

原文地址:https://www.cnblogs.com/xiaohaigege/p/5175148.html