class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = len(nums)
for i in range(n):
for j in range(i+1, n):
if nums[i] + nums[j] == target:
return [i, j]
return []
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i, num in enumerate(nums):
if target - num in dic:
return [dic[target-num], i]
else:
dic[num] = i
return []
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
for (int i = 0; i < n; ++i){
for (int j = i + 1; j < n; ++j){
if (nums[i] + nums[j] == target){
return {i, j}; // 怎么是这种形式呢
}
}
}
return {};
}
};
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> dic;
for (int i = 0; i < nums.size(); ++i){
auto it = dic.find(target - nums[i]); // auto 代替 迭代器类型, 提示编译器自动识别。简化代码
//这里等效于
//unordered_map::iterator it = dic.find(target - nums[i]);
if (it != dic.end()){
return {it->second, i}; // 注意 字典 的 find 函数 会同时返回 键和值
}
else{
dic[nums[i]] = i;
}
}
return {};
}
};
————————————
这样看来用 result 好些,因为不一定是正确答案。