HashMap with two nested loops into a single loop split

Title: an array of integers and a given target value target, identify two elements from the array, so that both the sum of the target value target, returns the array element number two. (Assuming target must solution per array element only once)
for example: int [] nums = {2,7,11,15 }, target = 9
sequence number returns an array [0,1]

Title from Leetcode

Answer 1: The most simple and crude answer, optimized degree of 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"); } } 

Answer 2: nested loop HashMap single split into two for loops

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!"); } } 

Best answer: a for loop, because the calculation of the target with two elements (two chances), the first unsuccessful certainly correct element will be saved to the map, to the second element can be read correctly.

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!"); } }

Reprinted link: https: //www.jianshu.com/p/e8cbe28c99b7

Guess you like

Origin www.cnblogs.com/open-source-java/p/10966279.html