Leetcodeブラシ問題小記(1)--T 1
1. Two Sum
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:
主にSTLライブラリのデータ構造unordered_を実行しました.map
vsテストコード:
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].
class Solution {
public:
vector twoSum(vector& nums, int target) {
unordered_map hash_table;
for (int i = 0; i < nums.size(); ++i){
if (hash_table.find(target - nums[i]) != hash_table.end())
return vector{ hash_table[target - nums[i]], i }; // 12ms beats 97.81%
hash_table.insert(pair(nums[i], i));
}
return vector();
}
};
主にSTLライブラリのデータ構造unordered_を実行しました.map
vsテストコード:
#include
#include
#include
using namespace std;
class Solution {
public:
vector twoSum(vector& nums, int target) {
unordered_map hash_table;
for (int i = 0; i < nums.size(); ++i) {
if (hash_table.find(target - nums[i]) != hash_table.end())
return vector{ hash_table[target - nums[i]], i }; // 12ms beats 97.81%
hash_table.insert(pair(nums[i], i));
}
return vector();
}
};
int main() {
Solution solution;
vector aaa{ 2,7,11,15 };
int target = 9;
cout << solution.twoSum(aaa, target)[0]<