1.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].
解决办法:
1:常规暴力搜索:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int len = nums.size();
for (int firstNum = 0; firstNum < len; firstNum ++)
{
for (int secondNum = firstNum+1; secondNum < len; secondNum++)
{
if (nums[firstNum]+nums[secondNum] == target)
{
vector<int> nums2;
nums2.push_back(firstNum);
nums2.push_back(secondNum);
return nums2;
}
}
}
}
};
暴力搜索:时间复杂度O(n^2)。
vector<int> nums2;
nums2.push_back(firstNum);
nums2.push_back(secondNum);
return nums2;
此部分可改为:return {firstNum, secondNum};
2:利用map,key和value的关系,可缩短时间复杂度:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
map<int, int> map;
for(int i=0; i < nums.size(); i++)
{
map.insert(pair<int, int>(nums[i], i));//将数组数字和位置存入map。
}
for (int i = 0; i < nums.size(); i++)
{
int otherNum = target - nums[i];
if (map.count(otherNum) && map.find(otherNum)->second != i) //查找key是否存在和不等于自己,避免4=2+2类似情况。
{
return {i, map.find(otherNum)->second};
}
}
return {};
}
};
map的count和find复杂度分析:近似为O(logN)
count,返回个数。如果有,返回1;否则,返回0。
find,返回位置,不存在则返回map.end()。
3:python:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
numDic = {}
for it in range(len(nums)):
if (target - nums[it]) in numDic:
return (numDic[target - nums[it]], it)
numDic[nums[it]] = it
此方法直接取值,判断,时间复杂度都在O(1),加上循环,总的时间复杂度O(N);