TwoSum
package LeetCode; import java.util.HashMap; import java.util.Map; /** * 1.两数之和: * 给定一个整数数组 nums和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那两个整数,并返回它们的数组下标。 * 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 * 你可以按任意顺序返回答案。 * * */ public class TwoSum { public static void main(String[] args) { int[] arr={1,4,6,7,8,3}; int target = 15; int[] array = twoSum(arr,target); for (int i = 0; i < array.length; i++) { System.out.print(array[i]+" "); } } public static int[] twoSum(int[] nums, int target) { // 利用哈希表 时间复杂度O(n) Map<Integer, Integer> 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}; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution"); } public int[] twoSum2(int[] nums, int target) { // 暴力穷举 时间复杂度O(n^2) int n = nums.length; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (nums[i] + nums[j] == target) { return new int[]{i, j}; } } } return new int[0]; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能