作者:力扣 (LeetCode) 链接:https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/x2jrse/ 来源:力扣(LeetCode)
题目描述:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例 1:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]答案v1.0
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> temp; // 方法1:使用暴力方法 /*for(int i = 0; i < nums.size(); i++) { for(int j = i + 1; j < nums.size(); j++) { if (nums[i] + nums[j] == target) { temp.push_back(i); temp.push_back(j); break; return temp; } } }*/ // 方法2:使用两次哈希表,对重复元素有问题,如[3, 3] /*map<int, int> tempHash; for(int i = 0; i < nums.size(); i++) //讲数组插入hash表 { tempHash.insert(pair<int, int>(nums[i], i)); } for( map<int, int>::iterator it0 = tempHash.begin(); it0 != tempHash.end(); it0++) //讲数组插入hash表 { map<int, int>::iterator it = tempHash.find(target - it0->first); while (it != tempHash.end() && it0->second != it->second) { temp.push_back(it0->second); temp.push_back(it->second); return temp; } }*/ // 方法3:使用一次哈希,先查找,再插入 map<int, int> tempHash; for(int i = 0; i < nums.size(); i++) //讲数组插入hash表 { map<int, int>::iterator it = tempHash.find(target - nums[i]); if (it != tempHash.end()) { temp.push_back(i); temp.push_back(it->second); return temp; } tempHash.insert(pair<int, int>(nums[i], i)); } return temp; } };存在问题:
方法2和方法3利用了hash表,hash底层对于数组的操作肯定也是和方法1类似,从这个角度而言方法2和方法3未必是最优解。况且方法2针对数组中重复元素,无法正常输出。