赞
踩
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].
题目的参数是一个vector和一个target,要求我们返回一个新的vector,新vector的内容保存初始vector中某两个元素加起来等于target的下标。(这里使用C++实现)
- class Solution {
-
- public:
-
- vector<int> twoSum(vector<int>& nums, int target) {
-
- vector<int>result;
-
- for(int i=0;i<nums.size();i++)
-
- {
-
- for(int j=i+1;j<nums.size();j++)
-
- {
-
- if(nums[i]+nums[j]==target)
-
- {
-
- result.push_back(i);
-
- result.push_back(j);
-
- }
-
- }
-
- }
-
- return result;
-
- }
-
- };

PS:这里的记录表为什么选择哈希表而不用数组,是因为查找的时候哈希表的效率比数组快,在查询表中是否已经存在满足条件的元素的时候,哈希表只需要o(1)的时间复杂度,而数组要o(n)。所以如果使用数组的话,时间复杂度和蛮力算法实际上是一样的。
- class Solution {
- public:
- vector<int>twoSum(vector<int>& nums, int target) {
- map<int,int>result;
- vector<int>v;
- for(int i=0;i<nums.size();i++)
- {
- int temp = target-nums[i];
- if(result.find(temp)!= result.end())
- {
- v.push_back(result[temp]);
- v.push_back(i);
- }
- result[nums[i]]=i;
- }
- return v;
- }
- };

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。