File tree Expand file tree Collapse file tree
main/java/com/crossoverjie/algorithm
test/java/com/crossoverjie/algorithm Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package com .crossoverjie .algorithm ;
22
3+ import java .util .HashMap ;
4+ import java .util .Map ;
5+
36/**
47 * Function:
58 *
912 */
1013public class TwoSum {
1114
15+ /**
16+ * 时间复杂度为 O(N^2)
17+ * @param nums
18+ * @param target
19+ * @return
20+ */
1221 public int [] getTwo1 (int [] nums ,int target ){
1322 int [] result = new int [2 ] ;
1423
@@ -24,4 +33,28 @@ public int[] getTwo1(int[] nums,int target){
2433 }
2534 return result ;
2635 }
36+
37+
38+ /**
39+ * 时间复杂度 O(N)
40+ * 利用Map Key存放目标值和当前值的差值,value 就是当前的下标
41+ * 每次遍历是 查看当前遍历的值是否等于差值,如果是等于,说明两次相加就等于目标值。
42+ * 然后取出 map 中 value ,和本次遍历的下标,就是两个下标值相加等于目标值了。
43+ *
44+ * @param nums
45+ * @param target
46+ * @return
47+ */
48+ public int [] getTwo2 (int [] nums ,int target ){
49+ int [] result = new int [2 ] ;
50+ Map <Integer ,Integer > map = new HashMap <>(2 ) ;
51+ for (int i =0 ;i <nums .length ;i ++){
52+
53+ if (map .containsKey (nums [i ])){
54+ result = new int []{map .get (nums [i ]),i } ;
55+ }
56+ map .put (target - nums [i ],i ) ;
57+ }
58+ return result ;
59+ }
2760}
Original file line number Diff line number Diff line change @@ -13,4 +13,13 @@ public void getTwo1() throws Exception {
1313
1414 }
1515
16+ @ Test
17+ public void getTwo2 (){
18+ TwoSum twoSum = new TwoSum () ;
19+ int [] nums ={1 ,3 ,5 ,7 };
20+ int [] two = twoSum .getTwo2 (nums , 4 );
21+ System .out .println (JSON .toJSONString (two ));
22+
23+ }
24+
1625}
You can’t perform that action at this time.
0 commit comments