"Power button" Question 1: "two numbers and" code (hash table)

"Power button" Question 1: "two numbers and" code

Method One: violence Solution

Java code:

public class Solution {

    public int[] twoSum(int[] nums, int target) {
        int len = nums.length;

        for (int i = 0; i < len - 1; i++) {
            for (int j = i + 1; j < len; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }

        throw new IllegalArgumentException("No two sum solution");
    }
}

Method Two: Use a lookup table

Java code:

import java.util.HashMap;
import java.util.Map;

public class Solution {

    public int[] twoSum(int[] nums, int target) {
        int len = nums.length;
        Map<Integer, Integer> hashMap = new HashMap<>(len - 1);
        hashMap.put(nums[0], 0);
        for (int i = 1; i < len; i++) {
            int another = target - nums[i];
            if (hashMap.containsKey(another)) {
                return new int[]{i, hashMap.get(another)};
            }
            hashMap.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}
Published 442 original articles · won praise 330 · Views 1.23 million +

Guess you like

Origin blog.csdn.net/lw_power/article/details/104066931