本題是一下公司的面試題:

問題描述:

 

問題求解:

使用無序容器unorder_map實現:

#include <iostream>
#include <vector>
#include <cassert>
#include <unordered_map>

using namespace std;

// 時間複雜度:O(n)
// 空間複雜度:O(n)
class Solution {
public:
	vector<int> twoSum(vector<int>& nums, int target) {

		unordered_map<int, int> record; //record表示元素的下標
		for (int i = 0; i < nums.size(); i++) {

			int complement = target - nums[i];  //complement為補數
			if (record.find(complement) != record.end()) { //在record中查詢元素complement
				int res[] = { i, record[complement] }; //將找到的兩個元素的下標放到陣列res中
				return vector<int>(res, res + 2);  //返回vector
			}

			record[nums[i]] = i; //將元素nums[i]放到record中,並將下標i計為record的value
		}

		throw invalid_argument("the input has no solution");//找不到答案,丟擲異常
	}
};


int main() {

	const int nums[] = { 2, 7, 11, 15};
	vector<int> nums_vec(nums, nums + sizeof(nums) / sizeof(int));
	int target = 9;

	vector<int> res = Solution().twoSum(nums_vec, target);
	cout << res[0] << " " << res[1] << endl;

	getchar();
	return 0;
}

 圖解:

①當 i = 0時:

②當 i = 1 時:

 

Reference: