标签:util example nbsp inpu lang 有一个 value void def
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Input: nums = [3,2,4], target = 6
Output: [1,2]
Input: nums = [3,3], target = 6
Output: [0,1]
给定一个数组和目标值,求数组中两个值相加等于目标值的索引下标,只会有一个解,且同一个数组元素不能使用两次。
本题主要考察哈希表的用法。
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
//key为值,value为数组下标
Map<Integer, Integer> map = new HashMap<>();
int[] res = new int[2];
for (int i = 0; i < nums.length; i++) {
int rest = target - nums[i];
if (map.containsKey(rest)) {
res[0] = i;
res[1] = map.get(rest);
break;
}
map.put(nums[i], i);
}
return res;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(new Solution().twoSum(new int[]{2, 7, 11, 15}, 9)));
System.out.println(Arrays.toString(new Solution().twoSum(new int[]{3, 2, 4}, 6)));
System.out.println(Arrays.toString(new Solution().twoSum(new int[]{3, 3}, 6)));
}
}
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums, target) {
var map = {};
for (var i = 0; i < nums.length; i++) {
var rest = target - nums[i];
if (map[rest] !== undefined) {
return [i, map[rest]];
}
map[nums[i]] = i;
}
return [];
};
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
map = {}
for i in range(len(nums)):
rest = target - nums[i]
if rest in map:
return [i, map.get(rest)]
map[nums[i]] = i
return []
标签:util example nbsp inpu lang 有一个 value void def
原文地址:https://www.cnblogs.com/strongmore/p/14263875.html