『LeetCode』1. 两数之和 Two Sum

题目描述

给定一个整数数组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
  • 只会存在一个有效答案

题目链接https://leetcode.cn/problems/two-sum/

『1』暴力解法

解题思路

最容易想到和简单粗暴的方法,即双重for循环:先枚举数组中的每一个数,再遍历数组在其之后的部分,若和等于target即返回结果。

实现代码:

class Solution {
// Brute Force
// N is the size of nums
// Time Complexity: O(N^2)
// Space Complexity: O(1)
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
int sum = nums[i] + nums[j];
if (sum == target) {
return new int[]{i, j};
}
}
}
return new int[0];
}
}

『2』哈希表法

解题思路

通过哈希容器HashMap能够快速寻找数组中是否存在目标元素,将时间复杂度降至O(1)。

实现代码:

class Solution {
// HashMap
// N is the size of nums
// Time Complexity: O(N)
// Space Complexity: O(N)
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int diff = target - nums[i];
if (map.containsKey(diff)) {
return new int[]{i, map.get(diff)};
}
map.put(nums[i], i);
}
return new int[0];
}
}
posted @   北岛孤影  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示