二、[LeetCode OJ]Two Sum題解

【問題描述】

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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
問題來源:Two Sum

【問題解析】

這個問題用兩個嵌套循環也能完成,但時間複雜度會是O(n^2),不是一個首選的算法。

考慮使用map<int,int>將遍歷後的數和它的下標存放,在一個循環遍歷下,利用map的標準庫函數find()去尋找滿足條件的數,時間複雜度只有O(n)。

【源代碼】

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
		map<int, int> hash;
		vector<int> result;
		for (int i=0; i < nums.size(); i++) {
			int numberToFind = target - nums[i];
			if (hash.find(numberToFind) != hash.end()) {
				result.push_back(hash[numberToFind]);
				result.push_back(i);
				return result;
			}
			hash[nums[i]] = i;
		} 
		return result;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章