愿每一天都陽光明媚
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].
大致意思:輸入一個數(shù)組和一個目標(biāo)數(shù),如果能在這個數(shù)組中找到兩個元素的和等于目標(biāo)數(shù)玻侥,那么就輸出這兩個數(shù)的下標(biāo)道伟,每次輸入用例時,都保證只有一個結(jié)果,每個元素使用一次蜜徽。
常規(guī)解法:兩層循環(huán)嵌套,依次遍歷票摇,每兩個元素都做一次相加運(yùn)算看是否等于目標(biāo)數(shù)拘鞋,直到找到這樣兩個數(shù),返回下標(biāo)矢门。時間復(fù)雜度太高盆色。
/**
Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
int arr=(int *)malloc(sizeof(int)3);
for(int i=0;i<numsSize;++i)
{
for(int j=i+1;j<numsSize;++j)
{
if(i!=j && nums[i]+nums[j]==target)
{
arr[0]=i;
arr[1]=j;
break;
}
}
}
return arr;
}
其他解法:
用哈希表,對數(shù)組進(jìn)行一次遍歷祟剔,每遍歷數(shù)組中的一個元素隔躲,就用目標(biāo)數(shù)減去該元素,看得到的結(jié)果是否存在哈希表中物延,如果不存在將該元素放入哈希表宣旱,繼續(xù)遍歷,直到找到結(jié)果在哈希表中叛薯,則找到這兩個元素浑吟,返回對應(yīng)下標(biāo)。時間復(fù)雜度相對較低耗溜。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> index;
unordered_map<int, int> hash;
for(int i=0; i<nums.size(); ++i) {
auto it = hash.find(target-nums[i]);
if(it != hash.end()) {
index.push_back(min(i, it->second)+1);
index.push_back(max(i, it->second)+1);
return index;
}
else hash[nums[i]] = i;
}
}
};