LeetCode-Two Sum

Description
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

第一种解法:使用暴力破解,对于每一个数字x,遍历数组,匹配是否有另外一个数字使得满足两数之和为target;

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 new int[] {i, j};
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

第二种解法:使用哈希表,第一次遍历数组时,将数组中的数字与下标作为键值对存储在表中,在第二次遍历数组的时候,查询表中是否存在另一个数为target与所查数字的差值;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> table = new HashMap<>();
        for(int i=0; i<nums.length; i++){
            table.put(nums[i], i);//key and indexs
        }
        for(int i=0; i<nums.length; i++){
            int result = target - nums[i];
            if(table.containsKey(result) && table.get(result) != i){
                return new int[] {i, table.get(result)};
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

第三种解法:同样是使用哈希表,与第二种不同的是,只需要遍历一遍数组,在遍历的时候,判断当前已存储的键值对中是否存在满足条件的键,若不存在,将当前的键值对插入,继续,至多遍历完一遍数组;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> table = new HashMap<>();
        for(int i=0; i<nums.length; i++){
            int result = target - nums[i];
            if(table.containsKey(result)){//当前键值对未插入,不必判断当前键是否冲突
                return new int[] {i, table.get(result)};
            }
            table.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/80882430