Skip to content

Commit 3546d8d

Browse files
author
刘勋
committed
两数之和
1 parent d2732e7 commit 3546d8d

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.algorithm.study.demo.algorithm.leetcode;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
/**
7+
* @author xun2.liu
8+
* @title: Solution17
9+
* @projectName algorithm-study
10+
* @description: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
11+
*
12+
* 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
13+
14+
* 示例:
15+
*
16+
* 给定 nums = [2, 7, 11, 15], target = 9
17+
*
18+
* 因为 nums[0] + nums[1] = 2 + 7 = 9
19+
* 所以返回 [0, 1]
20+
*
21+
* 来源:力扣(LeetCode)
22+
* 链接:https://leetcode-cn.com/problems/two-sum
23+
* @date 2020/5/28 15:54
24+
*/
25+
public class Solution17 {
26+
public static int[] twoSum(int[] nums, int target) {
27+
Map<Integer,Integer> map= new HashMap<>();
28+
for(int i=0;i<nums.length;i++){
29+
int temp=target-nums[i];
30+
if(map.containsKey(temp)){
31+
return new int[]{map.get(temp),i};
32+
}else{
33+
map.put(nums[i],i);
34+
}
35+
}
36+
throw new IllegalArgumentException("No two sum Solution");
37+
}
38+
39+
public static void main(String[] args) {
40+
int[] ints = twoSum(new int[]{1, 2, 3, 4, 5}, 4);
41+
for (int i = 0; i < ints.length; i++) {
42+
System.out.println(ints[i]);
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)