每日leetcode算法题:1两数之和
2023-09-11 14:20:00 时间
题目详情:
![](https://img-blog.csdnimg.cn/img_convert/ca84eaf0105192cf657177e93332135f.png)
![](https://img-blog.csdnimg.cn/img_convert/8adff683d88804fba775608023489e6c.png)
乍一看,直接双重循环多简单啊,将数组循环两次,然后if语句判断。直接上代码:
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for (int i=0; i<nums.length - 1; i++) {
for (int j=i+1; j<nums.length; j++) {
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
但是测试了一下,虽然通过了测试,但是执行结果却并不理想:
![](https://img-blog.csdnimg.cn/img_convert/e1e73b0362b3ef34e1daac8cff9b265a.png)
然后,然后开始了冥思苦想,该怎么才能提高用时和降低内存消耗?那就是将暴力解法双重for循环变成一层,想了好久好久终于get到一种思路利用HashMap 解,话不多说,看代码:
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i=0; i<nums.length; i++) {
if (map.containsKey(target - nums[i])) {
return new int[]{map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
return new int[0];
}
![](https://img-blog.csdnimg.cn/img_convert/9bbe9f1bea8fbb516f1165ed05b17566.png)
去掉for循环果然快了很多,但是内存消耗依然不小,如果有小伙伴有更好的解欢迎留言哦!
相关文章
- Java实现 LeetCode 739 每日温度(暴力循环)
- Java实现 LeetCode 587 安装栅栏(图算法转换成数学问题)
- Java实现 LeetCode 575 分糖果(看看是你的长度小还是我的种类少)
- Java实现 LeetCode 142 环形链表 II(二)
- Java实现 LeetCode 59 螺旋矩阵 II
- 【LeetCode算法-58/66】Length of Last Word/Plus One
- 【LeetCode算法-26】Remove Duplicates from Sorted Array
- 【LeetCode算法-21】Merge Two Sorted Lists
- 【LeetCode算法-14】Longest Common Prefix
- LeetCode-1684. 统计一致字符串的数目【哈希表,位运算】
- leetcode 17. 电话号码的字母组合----回溯算法
- leetcode 28. 实现 strStr()----KMP算法,朴素模式匹配算法----超万字长文详解
- leetcode算法第9题
- 【LeetCode 中等 字符串 python3】524 通过删除字母匹配到字典里最长单词
- 【LeetCode Python实现】34. 在排序数组中查找元素的第一个和最后一个位置(中等)
- Leetcode 1114. 按序打印
- Leetcode 6. Z 字形变换(牛逼,解决了)
- Leetcode四数之和终于解决
- Leetcode 36. 有效的数独(可以,一次过)
- [LeetCode] 109. 有序链表转换二叉搜索树 ☆☆☆(递归)
- LeetCode:Remove Duplicates from Sorted Array
- LeetCode之LRU Cache 最近最少使用算法 缓存设计
- 009-LeetCode算法解题总结分析
- 【LeetCode-面试算法经典-Java实现】【130-Surrounded Regions(围绕区域)】
- [LeetCode] Network Delay Time 网络延迟时间——最短路算法 Bellman-Ford(DP) 和 dijkstra(本质上就是BFS的迭代变种) 动态规划,要会模板!
- LeetCode 141. 环形链表