Algorithm/src/main/java/hash/TwoSum.java

29 lines
1.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package hash;
import java.util.HashMap;
/**
* 题目1.两数之和 (Two Sum)
* 描述:给定一个整数数组 nums 和一个目标值 target请你在该数组中找出和为目标值的那两个整数并返回它们的数组下标。
* 链接https://leetcode.cn/problems/two-sum/
*
* 示例 1
*
* 输入nums = [2,7,11,15], target = 9
* 输出:[0,1]
* 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
*/
//做出来了。
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i]; // 计算补数
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i}; // 返回补数的索引和当前索引
}
map.put(nums[i], i); // 将当前元素和索引存入 map
}
throw new IllegalArgumentException("No two sum solution"); // 如果没有解,抛出异常
}
}