leetcode1 两数之和
两数
2023-09-27 14:25:55 时间
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
思路:不能双指针,因为排序后无法知道下标。
遇到的数字装到hashmap中,遇到的新数字查找有没有答案int dif = target - nums[i];
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<>();
int[] res = new int[2];
for (int i = 0; i < nums.length; i++) {
int dif = target - nums[i];
if (map.get(dif) != null) {
res[0] = map.get(dif);
res[1] = i;
return res;
}
map.put(nums[i],i);
}
return res;
}
}
相关文章
- Newtonsoft.Json C# Json序列化和反序列化工具的使用、类型方法大全 C# 算法题系列(二) 各位相加、整数反转、回文数、罗马数字转整数 C# 算法题系列(一) 两数之和、无重复字符的最长子串 DateTime Tips c#发送邮件,可发送多个附件 MVC图片上传详解
- LeetCode高频题1:两数之和
- C++第7周任务1-求两数正差值
- [算法]两数之和,三数之和
- [LeetCode]167. 两数之和 II - 输入有序数组
- LeetCode 167. 两数之和 II - 输入有序数组
- 【leetcode】力扣 --- 日积月累,每日一题——1 两数之和
- 华为OD机试 - 乱序整数序列两数之和绝对值最小(JavaScript) | 机试题+算法思路+考点+代码解析 【2023】
- [LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树
- [LeetCode] Two Sum II - Input array is sorted 两数之和之二 - 输入数组有序
- Python算法练习之解决两数之和问题