1. 程式人生 > >LeetCode 之 Two Sum — C++ 實現

LeetCode 之 Two Sum — C++ 實現

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

給定一個整型陣列,找出和為給定目標值的兩個數。

函式返回這兩個數的索引,index1 必須小於 index2。注意,返回的索引不是從 0 開始的。

假設對於每個輸入只有一個解。

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

分析

    使用 map,鍵為陣列值,值為陣列索引

。用target減去陣列值,然後在 map 中查詢這個差值,如果存在,則返回兩個索引;不存在,將此陣列值存入 map 中,重複此過程指導查詢完陣列為止。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        if(nums.empty())//空
        {
            return vector<int>();
        }
        
        map<int, int> addend;
        int numsSize = nums.size();
        for(int index = 0; index < numsSize; ++index)
        {
            if(addend.find(target - nums[index]) == addend.end())//另一個加數不在 map 中,加入 map
            {
                addend[nums[index]] = index + 1;
            }
            else //找到兩個合法的數
            {
                vector<int> ret;
                ret.push_back(addend[target - nums[index]]);
                ret.push_back(index + 1);
                
                return ret;
            }
        }
        
        return vector<int>();
    }
};