leetcode-1. 两数之和

题目介绍

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

输入:nums = [3,2,4], target = 6
输出:[1,2]

示例 3:

输入:nums = [3,3], target = 6
输出:[0,1]

提示:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案

思路

第一个想法就是暴力解法,当然时间复杂度也就是O(n2)。暴力想法不用说,两个for循环搞定。

暴力解法代码

// 暴力解法
    public static int[] twoSum01(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};
                }
            }
        }
        return new int[0];
    }

第二个想法就是leetcode给的用哈希表。可以将targe - num[i]作为key值,索引值作为value值。首先判断哈希表是否存在targe - num[i],如果有,则通过targe - num[i]获取到索引值,并返回索引值和i,如果没有则将当前num[i]存入到哈希表。因为2+77+2一样。所以只需要考虑存入到哈希表的值,不用考虑后续值。

哈希表代码

// 使用哈希表
    // 以target - nums[i]为key值,以nums[i]为value
    public static int[] twoSum02(int[] nums, int target){
        HashMap<Integer,Integer> hashTable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (hashTable.containsKey(target - nums[i])){
                return new int[] {hashTable.get(target - nums[i]),i};
            }
            hashTable.put(nums[i],i);
        }
        return new int[0];

    }
posted @ 2022-06-09 11:24  littlemelon  阅读(25)  评论(0编辑  收藏  举报