leetcode.1. two numbers

 

------- extremely personal records to the question of do -------

Application of the hash table.

Thinking: ① array nums [i] stored hash table

     ② each time look into (target-a [i]) if the hash table is also not as nums [i] itself

 

Error-prone alert: map.get (key) function to find the key value is needed, so that taking into account the through (target-a [i]) to find whether the array index i corresponding to itself, the addition of key-value pairs time,

 

Format should be "map.put (nums [i], i)"

Code:

public int[] twoSum(int[] nums, int target) {
        The HashMap <Integer, Integer> Map = new new the HashMap <> ();
         int A [] = {0,0 };
         for ( int I = 0; I <nums.length; I ++ ) {
             int X = target- the nums [I ];
             IF (map.containsKey (X) = I as map.get && (X)!) { // If there is not the subtrahend minuend itself 
                A [0] = I;
                a[1]=map.get(x);
                break;
            }else {
                map.put(nums[i],i);
            }
        }
        return a;
    }

Conclusion: The experience is essentially a re-check or quickly find problems, consider using a hash table.

 

 

Guess you like

Origin www.cnblogs.com/hdrawery/p/11980455.html