用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

posted @ 2019-06-03 10:51  小小脑袋  阅读(621)  评论(0编辑  收藏  举报