Two sum problem solution in leetcode

I have to say that the level is still too bad. The first two for loops were used to solve the problem directly. Although the result was obtained, some people on the Internet have already said that the problem cannot be solved by violence, so they can only seek another solution. Occasionally saw a netizen mention that hashmap can be used to solve it, so I searched the Internet to find the use of hashmap, because I have never contacted it before. . . . I finally solved this problem, hahaha, so happy.

import java.util.HashMap;

public class TwoSum {
    public static int[] twoSum(int[] nums,int target) {
        HashMap <Integer,Integer> m = new HashMap<Integer,Integer>(); // Create a hashmap object 
        int []res = new  int [ 2 ]; // Create an array to store the index of the array 
        for ( int i = 0 ; i < nums.length;++i) { // loop     
            if (m.containsKey(target - nums[i])) { // Determine whether the array exists and the value of target-nums[i], if it exists, 
                res[ 0 ] = i;
                res[1] = m.get(target - nums[i]);
                break;
            }
            m.put(nums[i], i); // Add the values ​​and subscripts in the array to the hashmap 
        }
         return res;
    }    
    public static void main(String[] args) {
        int[] s = {2,5,8,9};
        int[] re = twoSum(s,7);System.out 
        .println ( " re1= " + re[ 0 ] + " ,re2= " + re[ 1 ]); // output subscript 
    }
}

Before writing it, I

m.put(nums[i], i);//Add the value and subscript in the array to the hashmap

Put this sentence before the loop, and then use another loop to put the values ​​of sums one by one. Although there is no problem during the test, it does not take into account the sum of the same number in the array, so it appears when submitting Answer the wrong situation, so you can only put the code in the for loop, come in to see if it is equal to target-sums[i], and then put the number and subscript into the hashmap, so that the above will not appear. that question.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324918862&siteId=291194637