用HashMap将两个嵌套循环拆成一个单循环

题目:给出一个整数数组和一个目标值target,从数组中找出两个元素,使这两者之和为目标值target,返回数组中这两个元素的序号。(假设target必有解,每个数组元素只用一次)
例如:int[] nums={2,7,11,15} , target=9
则返回数组中序号 [0,1]

题目源自Leetcode

答案1:最简单粗暴的答案,优化度为O(n2)

class Solution{
  public int[] twoSum(int[] nums,int target){ for (int i=0;i<nums.length;i++){ for(int j=0;j<nums.length;j++){ nums[i] = target- nums[j]; return new int[] {i,j}; } } //没有return所以要抛出异常 throw new IllegalArgumentException("Something wrong with input parameters"); } } 

答案2:通过HashMap将嵌套循环拆成两个单for循环

class Solution {
  public int[] twoSum(int[] nums, int target){ 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 complement = target-nums[j]; if(map.containsKey(complement)&&(int)map.get(complement)!=j){ return new int[]{map.get(nums[j]), j}; } } throw new IllegalArgumentException("No such solution!"); } } 

最优答案:一个for循环,因为要计算的 target 有两个元素(两次机会),第一个正确的元素肯定不成功会被保存到map中,到第二个正确元素可以读取到。

class Solution {
    public int[] twoSum(int[] nums, int target){ Map map=new HashMap(); for(int i=0;i<nums.length;i++){ int complement=target -nums[i]; if(map.containsKey(complement)){ return new int[]{i,(int)map.get(complement)}; } map.put(nums[i],i); } throw new IllegalArgumentException("No such solution!"); } }

转载链接:https://www.jianshu.com/p/e8cbe28c99b7

转载于:https://www.cnblogs.com/open-source-java/p/10966279.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值