程序员LeetCode Amazing

1.TwoSum

2020-10-14  本文已影响0人  93张先生

题目

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

题解

暴力破解法

双重 for 循环遍历数组,求两个数之和,然后和目标数对比。重点在于已经使用过的数字,不能使用两边,所以 j 的初始值为 i +1 。

代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] indexs = new int[2];
        if(nums != null && nums.length > 0){
            for(int i = 0; i < nums.length; i++){
                for(int j = i + 1; j < nums.length; j++){
                    if(nums[i] + nums[j] == target){
                        indexs[0] = i;
                        indexs[1] = j;
                        return indexs;
                    }
                }
            }
        }
        return new int[0];
    }
}
哈希表法

查找方法:目标数 target 减去,数组中的一个元素,然后和已经放入 HashMap 中的数字进行对比,是否相等,HashMap 中的数字是这个将要放入 HashMap 数字之前的所有数字。

image.png

代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
    Map<Integer,Integer> hashMap = new HashMap<Integer,Integer>();
        for(int i = 0; i < nums.length; i++){
            if(hashMap.containsKey(target - nums[i])){
                return new int[]{hashMap.get(target - nums[i]),i};
            }
            // 重点
            hashMap.put(nums[i],i);
        }
        return new int[0];
    }
}
上一篇 下一篇

猜你喜欢

热点阅读