leetcode 两数之和 java
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
第一种是冒泡查找,但不能是同一个数字;
class Solution { public int[] twoSum(int[] nums, int target) { int[] a = new int[2]; for(int i = 0; i < nums.length; i++){ int res = target - nums[i]; for(int j = 0; j < nums.length; j++){ if(res ==nums[ j] && i != j){ a[0] = i; a[1] = j; return a; } } } return a; } }
第二种:用Hash
为了使得代码的复杂度降低,我们可以采取第二种形式,是通过java中的hashmap 的方法,在这里无基础的也将可以使用hashmap 的用法Map <Integer,Integer> map = new HashMap<>();
map.put 是将键值推入
map.containsKey 是找到值,
而map.get 是获取键
class Solution { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; Map <Integer,Integer> map = new HashMap<>(); for(int i = 0 ; i < nums.length; i++){ map.put(nums[i],i); } for(int j = 0; j < nums.length; j++){ int k = target - nums[j]; if(map.containsKey(k) && j != map.get(k)){ result[0] =j; result[1] = map.get(k); return result; } } return result; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律