difficult:easy #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 暴力法
时间复杂度 O()
std::vector<int> sum::twoSum(std::vector<int>& nums, int target){
std::vector<int> result;
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
int sum = nums[i] + nums[j];
if (sum == target) {
result.push_back(i);
result.push_back(j);
}
}
}
return result;
}
解法2 HashMap
时间复杂度 O()
vector<int> twoSum(vector<int>& nums, int target) {
std::map<int,int> nums_map;
std::vector<int> result;
for (int i = 0; i < nums.size(); i++){
nums_map[nums[i]] = i;
}
for (int i = 0; i < nums.size(); i++){
int value = target - nums[i];
if (nums_map.find(value) != nums_map.end() && nums_map[value] != i) {
result.push_back(i);
result.push_back(nums_map[value]);
return result;
}
}
}
版权声明:原创,转载请注明来源,否则律师函警告
本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!