题目:
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
你可以按任意顺序返回答案。
示例:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
题解思路:
1、暴力运算,耗时较长
2、哈希查找,一次对应
public static int[] twoSum(int[] nums, int target) {
//暴力运算,耗时较长
/* int total;
for (int i = 0; i < nums.length; i++) {
for (int j = i+1; j < nums.length; j++) {
total = nums[i]+nums[j];
if (total==target){
return new int[]{i, j};
}
}
}*/
// 哈希查找,一次对应
int[] arr = new int[2];
HashMap<Integer, Integer> hashMap = new HashMap<>(10);
for (int i = 0; i < nums.length; i++) {
if (hashMap.containsKey(nums[i])){
arr[0] = hashMap.get(nums[i]);
arr[1] = i;
return arr;
}
hashMap.put(target-nums[i],i);
}
return null;
}
题目来源:力扣-两数之和
该博客讨论了一道编程题目,即在给定整数数组中找到和为目标值的两个整数的下标。传统的暴力解法效率低下,而通过哈希查找可以显著提高效率。博客提供了一个使用哈希表的解决方案,通过一次遍历数组,将目标值减去当前元素的值作为键,元素的下标作为值存入哈希表,如果键已存在则直接返回答案。这种方法减少了时间复杂度,提高了算法性能。
13万+

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



