方法一:暴力枚举
class Solution {
public int[] twoSum(int[] nums, int target) {
//定义一个变量n存储数组长度
int n = nums.length;
//遍历数组中的每一个数
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
//判断target-x是否等于x之后的数
if (nums[i] + nums[j] == target) {
//返回一个存放target-x和x的下标的新数组
return new int[]{i, j};
}
}
}
//函数需要一个数组返回值
return new int[0];
}
}
方法二:哈希表
class Solution {
public int[] twoSum(int[] nums, int target) {
//定义一个哈希表,容量为数组长度-1
Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>(nums.length-1);
//遍历数组
for (int i = 0; i < nums.length; i++) {
//判断哈希表中是否存在target-x的元素及其下标
if (hashtable.containsKey(target - nums[i])) {
//返回一个包含target-x的下标和x的下标的新数组
return new int[]{hashtable.get(target - nums[i]), i};
}
//不存在的话将这个x元素存入哈希表中
hashtable.put(nums[i], i);
}
//函数需要一个数组返回值
return new int[0];
}
}
这篇博客介绍了在给定整数数组和目标值的情况下,如何找到数组中两个数,使得它们的和等于目标值。文章提供了两种解决方案:第一种是暴力枚举法,通过双重循环遍历数组;第二种是使用哈希表,提高查找效率,避免重复计算。这两种方法分别展示了不同的算法思路和时间复杂度。
1210

被折叠的 条评论
为什么被折叠?



