# 1、两数之和

1）暴力破解，遍历每个元素 x

 1 class Solution {
2     public int[] twoSum(int[] nums, int target) {
3         for (int i = 0; i < nums.length; i++) {
4             for (int j = i + 1; j < nums.length; j++) {
5                 if (nums[j] == target - nums[i]) {
6                     return new int[] { i, j };
7                 }
8             }
9         }
10         throw new IllegalArgumentException("No two sum solution");
11     }
12 }
View Code

2）通过循环遍历两次哈希表，第一次添加全部元素，第二次通过减去元素，查找另外一个是否在哈希表里面。

 1 class Solution {
2     public int[] twoSum(int[] nums, int target) {
3         Map<Integer, Integer> map = new HashMap<>();
4         for (int i = 0; i < nums.length; i++) {
5             map.put(nums[i], i);
6         }
7         for (int i = 0; i < nums.length; i++) {
8             int complement = target - nums[i];
9             if (map.containsKey(complement) && map.get(complement) != i) {
10                 return new int[] { i, map.get(complement) };
11             }
12         }
13         throw new IllegalArgumentException("No two sum solution");
14     }
15 }
View Code

3）循环遍历一次哈希表，每插入一个元素，查看哈希表里面是否含有目标元素，及是否含有target-x，具体上代码：

 1 class Solution {
2     public int[] twoSum(int[] nums, int target) {
3         Map<Integer, Integer> map = new HashMap<>();
4         for (int i = 0; i < nums.length; i++) {
5             int complement = target - nums[i];
6             if (map.containsKey(complement)) {
7                 return new int[] { map.get(complement), i };
8             }
9             map.put(nums[i], i);
10         }
11         throw new IllegalArgumentException("No two sum solution");
12     }
13 }
View Code
posted @ 2020-01-08 00:54  Alos403  阅读(387)  评论(0编辑  收藏  举报