File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
src/main/java/com/geekidentity/leetcode/n0001 Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .geekidentity .leetcode .n0001 ;
2
+
3
+ import java .util .HashMap ;
4
+ import java .util .Map ;
5
+
6
+ /**
7
+ * 1. 两数之和
8
+ * https://leetcode-cn.com/problems/two-sum/
9
+ */
10
+ public class TwoSum {
11
+
12
+ public int [] twoSum1 (int [] nums , int target ) {
13
+ for (int i = 0 ; i < nums .length - 1 ; i ++) {
14
+ for (int j = i + 1 ; j < nums .length ; j ++) {
15
+ if (nums [i ] + nums [j ] == target ) return new int []{i , j };
16
+ }
17
+ }
18
+ return new int [0 ];
19
+ }
20
+
21
+ public int [] twoSum2 (int [] nums , int target ) {
22
+ Map <Integer , Integer > map = new HashMap <>(nums .length );
23
+
24
+ for (int i = 0 ; i < nums .length ; i ++) {
25
+ int diff = target - nums [i ];
26
+ if (map .containsKey (diff )) {
27
+ return new int []{i , map .get (diff )};
28
+ }
29
+ map .put (nums [i ], i );
30
+ }
31
+ return new int [0 ];
32
+ }
33
+ }
You can’t perform that action at this time.
0 commit comments