LeetCode-Java 1.TwoSum
2022-6-22
刚刚学完了Java的基本语法,第一天开始刷LeetCode啦
- Two Sum
Easy
336471063Add to ListShare
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have *exactly* one solution, and you may not use the same element twice.
You can return the answer in any order.
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
看到题目就是想到用两个for循环来求解,,于是:
class Solution {
public int[] twoSum(int[] nums, int target) {
int res[] = new int[2];
a1: for (int i = 0; i < nums.length-1; i++)
{
for (int j = i+1; j <nums.length ;j++){
if (nums[i] + nums[j] == target){
res[0] = i;
res[1] = j;
break a1;
}
}
}
return res;
}
}
但是这样执行效率并不高,运行时间很长,内存使用还好。百度一下,好像大家都用的hash方法求解的。
然后去看了一下这篇文章(https://blog.youkuaiyun.com/xqs196301/article/details/123095920),但是还是对hash table理解不是特别深刻,但是大致了解了一下。可以将要比对的数视为关键字,这样就不必每次循环就进行一次比较,就像是将数组的索引和值对调了一下。下面是用HashMap方法写的代码:
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i= 0; i< nums.length ; i++){
if (map.get(nums[i]) == null)
map.put(target-nums[i],i);
else
return new int[]{map.get(nums[i]),i};
}
return null;
}
}
最后终于提交成功啦!
博主分享了初次尝试LeetCode的Java解题经历,从最初的双重循环解法到采用HashMap优化,提高了算法效率。文章通过两个示例解释了两数之和问题,并提供了两种不同的解决方案,重点讨论了HashMap在解决此类问题中的应用。

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



