给定一个数组和一个数字,找出数组中的两个值加起来等于这个数字
给定一个数组和一个数字,找出数组中的两个值加起来等于这个数字
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
// 方法:寻找数组中两个数相加等于目标值的索引
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numMap = new HashMap<>(); // 创建哈希表用于存储已遍历过的数值及其索引
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i]; // 计算当前元素与目标值的差值
// 如果差值存在于哈希表中,说明我们找到了一对解
if (numMap.containsKey(complement)) {
return new int[]{numMap.get(complement), i}; // 返回这两个数的索引
}
// 将当前元素存入哈希表,以便后续查找其是否能与其他元素构成目标和
numMap.put(nums[i], i);
}
// 如果没有找到符合条件的数对,返回一个空数组或其他表示未找到的值
return new int[0];
}
// 主方法,用于测试
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int target = 9;
int[] result = twoSum(nums, target);
if (result.length == 2) {
System.out.println("Indices of the two numbers that add up to " + target + ": [" + result[0] + ", " + result[1] + "]");
} else {
System.out.println("No two sum solution found.");
}
}
}
偶做前堂客
祝你天天开心
在未知的时间
在未知的地点
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了