两数之和

101 阅读1分钟

题目编号1:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

1、暴力法

思路:双重循环遍历数组

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length-1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == target - nums[i]) {
                    return new int[] { i, j };
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

2、两遍hash法

第一遍把所有的值都存放到hash表中,第二遍直接取值对比

class Solution {
    public int[] twoSum(int[] nums, int target) {

        //利用hash表  时间复杂度O(n)
        Map<Integer,Integer> map = new HashMap<>();
        for (int i=0; i<nums.length; i++) {
            map.put(nums[i],i);
        }

        for (int i=0; i<nums.length; i++) {
            Integer position = target - nums[i];
            if (map.containsKey(position) && i != map.get(position)) {
                return new int[]{i,map.get(position)};
            }
        }
        throw new RuntimeException("没有找到合法的数据");
    }
}

3、一遍hash法

在put进hash表的时候就判断符合条件的数据是否存在hash表中

class Solution {
    public int[] twoSum(int[] nums, int target) {

        //利用hash表  时间复杂度O(n)
        Map<Integer,Integer> map = new HashMap<>();
        for (int i=0; i<nums.length; i++) {
            int position = target - nums[i];
            if (map.containsKey(position)){
                return new int[]{i,map.get(position)};
            }
            map.put(nums[i],i);
        }

        throw new RuntimeException("没有找到合法的数据");
    }
}