英文:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
中文:
给出一组整数,找出其中两个元素,它们的和为我们指定的某个数字,实现函数返回这两个元素从1开始计算的位置,返回值要求第一个数字小于第二个数字。假设给出的数组只有一组解。
例如:给出数组{2, 7, 11, 15},指定的数字是9,则应该返回1和2,因为第一个数字2加上第二个数字7的和是9
public class Solution { /** * 给出指定数组,其中两数字相加之和等于目标数字,求出这两个数字的序号 * @param nums 输入数组 * @param target 目标数字 * @return */ public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { if (hashMap.containsKey(nums[i])) { return new int[] { hashMap.get(nums[i]) + 1, i + 1 }; } else { hashMap.put(target - nums[i], i); } } return new int[] { 0, 0 }; }}
本文介绍了一种高效解决两数之和问题的算法。通过使用HashMap存储目标值与当前值的差及其索引,实现了快速查找配对值的功能。这种方法确保了在数组中找到唯一的一对数字,使它们的和等于给定的目标值。

被折叠的 条评论
为什么被折叠?



