diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000000000000000000000000000000000000..69a4ff5a3ae3d3065e906802a4ab540b38c37c13 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,36 @@ + + + + \ No newline at end of file diff --git a/src/Main.java b/src/Main.java deleted file mode 100644 index a0428dacd1cebc7f0563c2ecda52facd35704f9b..0000000000000000000000000000000000000000 --- a/src/Main.java +++ /dev/null @@ -1,6 +0,0 @@ -public class Main { - - public static void main(String[] args) { - System.out.println("Hello World!"); - } -} diff --git a/src/easy/LeetCode0001.java b/src/easy/LeetCode0001.java new file mode 100644 index 0000000000000000000000000000000000000000..8aa323a54e620205beb5ff85dc080a125143981a --- /dev/null +++ b/src/easy/LeetCode0001.java @@ -0,0 +1,49 @@ +package easy; + +import java.util.HashMap; +import java.util.Map; + +/** + * 1. 两数之和 + * 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 + * 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 + * 示例: + * 给定 nums = [2, 7, 11, 15], target = 9 + * 因为 nums[0] + nums[1] = 2 + 7 = 9 + * 所以返回 [0, 1] + * + * @ClassName leetCode0001 + * @Description TODO:完成算法 + * @Author Long + * @Date 2020/10/20 8:46 + * @Version 1.0 + */ +public class LeetCode0001 { + + public static void main(String[] args) { + int[] nums = {2, 7, 11, 15}; + int target = 9; + int[] result = new LeetCode0001().useMap(nums,target); + for (int num:result) { + System.out.print(num + "\t"); + } + } + + /** + * 使用Map实现 + * @param nums 传入数组 + * @param target 检查值 + * @return 返回 + */ + private int[] useMap(int[] nums, int target) { + Map 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]; + } +}