Leetcode: Two Sum
LeetCode sum two
2023-09-11 14:14:08 时间
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
One-pass Hash Table
class Solution { public int[] twoSum(int[] nums, int target) { int[] res = new int[2]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(target - nums[i])) { res[1] = i; res[0] = map.get(target - nums[i]); return res; } map.put(nums[i], i); } return res; } }
相关文章
- Java实现 LeetCode 780 到达终点(逻辑题)
- Java实现 LeetCode 653 两数之和 IV - 输入 BST(递归,找差值)
- Java实现 LeetCode 594 最长和谐子序列(滑动窗口)
- Java实现 LeetCode 820 单词的压缩编码(字典树)
- Java实现 LeetCode 503 下一个更大元素 II
- Java实现 LeetCode 187 重复的DNA序列
- Java实现 LeetCode 109 有序链表转换二叉搜索树
- Java实现LeetCode_0001_Two Sum
- (LeetCode 64)Minimum Path Sum
- [LeetCode] Binary Tree Paths
- leetcode 面试题 17.16. 按摩师
- LeetCode 1. Two Sum
- 【LeetCode Python实现】356. 直线镜像(中等)
- Leetcode 1114. 按序打印
- Leetcode 1089. 复写零
- Leetcode 1614. 括号的最大嵌套深度
- [LeetCode] 39. Combination Sum ☆☆☆(数组相加等于指定的数)
- Leetcode--Two Sum
- leetcode 437. Path Sum III
- 【Leetcode刷题Python】LeetCode 478. 在圆内随机生成点
- 【Leetcode刷题Python】 LeetCode 2038. 如果相邻两个颜色均相同则删除当前颜色
- 【Leetcode刷题Python】剑指 Offer 18. 删除链表的节点