力扣历程
这篇笔记用于记录在力扣刷题的历程、想法等,不过也会有其他平台的题。
2026.9
两数之和
给定一个整数数组nums和一个整数目标值target,请你在该数组中找出 和为目标值target的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
你可以按任意顺序返回答案。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| #include <vector> #include <unordered_map>
using namespace std;
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> num_map; for (int i = 0; i < nums.size(); ++i) { int complement = target - nums[i]; auto it = num_map.find(complement); if (it != num_map.end()) { return {it->second, i}; } num_map[nums[i]] = i; } return {}; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import java.util.HashMap; import java.util.Map;
class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[] { map.get(complement), i }; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution"); } }
|