Title description:

Given an integer array nums and an integer target value target, find the two integers in the array and the target values and return their array subscripts.

You can assume that there is only one answer for each type of input. However, the same element in the array cannot be repeated in the answer. You can return the answers in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9 output: [0,1]

Solution 1: Traverse the array twice, violent solution

class Solution {
    public int[] twoSum(int[] nums, int target) {
        
        for(int i = 0; i < nums.length; i++) {for(int j = i + 1; j < nums.length; j++) {if(nums[i] + nums[j] == target) {
                    return newint[]{i, j}; }}}return null; }}Copy the code

Solution 2: hash table

        int[] indexs = new int[2];
        // create a k-v hash table
        HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
        for(int i = 0; i < nums.length; i++){
            if(hash.containsKey(nums[i])){
                indexs[0] = i;
                indexs[1] = hash.get(nums[i]);
                return indexs;
            }
            // store data to key as complement and value as subscript
            hash.put(target-nums[i],i);
        }
Copy the code