LeetCode--HOT100题(1)

目录

  • 题目描述:1. 两数之和(简单)
    • 题目接口
    • 解题思路1
      • 代码
    • 解题思路2
      • 代码
  • PS:

题目描述:1. 两数之和(简单)

给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值target的那 两个整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。

LeetCode做题链接:LeetCode-两数之和

示例 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) 的算法吗?

题目接口

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

    }
}

解题思路1

遍历双重循环遍历数组,然后把i,j下标对应的值相加起来,等于目标值,返回

代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
		for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums.length; j++) {
                if(nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }
}

在这里插入图片描述
成功!
两层for循环查找,时间复杂度是O(n^2)。

解题思路2

思路:
使用map集合的map.containsKey()方法,是否包含这个键。数组中的元素作为key,下标作为value。
每次遍历的时候,将target减去当前遍历的下标的值,得到一个temp,再使用map.containsKey()方法匹配:

  • 匹配不到,将本次循环的num[i],i放进map中,因为map存放的就是我们访问过的元素。
  • 匹配到,存放到结果中

代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
   		int[] res = new int[2];
        if(nums == null || nums.length == 0){
            return res;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++){
            int temp = target - nums[i];
            if(map.containsKey(temp)){
                // 匹配到,意思就是当前的num[i] + temp = target 分别对应的下标是:i, map.get(temp)
                res[1] = i;
                res[0] = map.get(temp);
            }
            // temp在map中没有匹配到,就存入map中
            map.put(nums[i], i);
        }
        return res;
    }
}

在这里插入图片描述
成功!
因为只使用了一个for循环,所以 速度快了很多,时间复杂度也小于O(n^2)。

PS:

感谢您的阅读!如果您觉得本篇文章对您有所帮助,请给予博主一个喔~

你可能感兴趣的:(LeetCodeHot100,leetcode,算法,java)