File tree 1 file changed +54
-0
lines changed
src/com/blankj/easy/_0001 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Arrays ;
2
+ import java .util .HashMap ;
3
+
4
+ /**
5
+ * @author luojing
6
+ * @description LJSolution
7
+ * @date 2022/07/15
8
+ */
9
+
10
+ public class LJSolution {
11
+
12
+ /**
13
+ * Solution1
14
+ * @param nums
15
+ * @param target
16
+ * @return
17
+ */
18
+ public int [] twoSum1 (int [] nums , int target ) {
19
+ for (int i = 0 ; i < nums .length ; i ++) {
20
+ for (int j = 0 ; j < nums .length ; j ++) {
21
+ if (nums [i ] + nums [j ] == target ) {
22
+ return new int [] {i , j };
23
+ }
24
+ }
25
+ }
26
+ return null ;
27
+ }
28
+
29
+ /**
30
+ * Solution2
31
+ * @param nums
32
+ * @param target
33
+ * @return
34
+ */
35
+ public int [] twoSum2 (int [] nums , int target ) {
36
+ int length = nums .length ;
37
+ HashMap <Integer , Integer > map = new HashMap <>();
38
+ for (int i = 0 ; i < length ; i ++) {
39
+ final Integer value = map .get (nums [i ]);
40
+ if (value != null ) {
41
+ return new int [] { value , i };
42
+ }
43
+ map .put (target - nums [i ], i );
44
+ }
45
+ return null ;
46
+ }
47
+
48
+ public static void main (String [] args ) {
49
+ LJSolution ljSolution = new LJSolution ();
50
+ int [] nums = new int [] {2 , 7 , 11 , 15 };
51
+ int target = 9 ;
52
+ System .out .println (Arrays .toString (ljSolution .twoSum1 (nums , target )));
53
+ }
54
+ }
You can’t perform that action at this time.
0 commit comments