一、Java
- import java.util.HashMap;
-
- class Solution {
- public int[] twoSum(int[] nums, int target) { //返回数组
- HashMap
map = new HashMap<>(); //键:元素值;值:元素索引 - for (int i = 0; i < nums.length; i++) {
- if (map.containsKey(target - nums[i]))
- return new int[]{map.get(target - nums[i]), i};
- else
- map.put(nums[i], i);
- }
- return null;
- }
- }
二、C++
- #include
- #include
- using namespace std;
- class Solution {
- public:
- vector<int> twoSum(vector<int>& nums, int target) {
- unordered_map<int, int> m; //unordered_map:哈希映射
- for (int i = 0; i < nums.size(); i++) {
- if (m.find(target - nums[i]) != 0)
- return {m[target - nums[i]], i};
- else
- m.insert({nums[i], i});
- }
- return {};
- }
- };
三、Python
- from typing import List
-
-
- class Solution:
- def twoSum(self, nums: List[int], target: int) -> List[int]:
- m = {}
- for i in range(len(nums)):
- if target - nums[i] in m:
- return [m[target - nums[i]], i]
- else:
- m[nums[i]] = i
四、JavaScript
- var twoSum = function(nums, target) {
- let m = new Map();
- for (let i = 0; i < nums.length; i++) {
- if ( m.has(target - nums[i]))
- return [m.get(target - nums[i]), i];
- else
- m.set(nums[i], i);
- }
- };
五、Go
- package main
-
- func twoSum(nums []int, target int) []int {
- m := make(map[int]int)
- for i := 0; i < len(nums); i++ {
- if idx, ok := m[target-nums[i]]; ok {
- return []int{idx, i}
- } else {
- m[nums[i]] = i
- }
- }
- return []int{}
- }