Skip to content

Commit 7bd2172

Browse files
committed
测试 加上注释
1 parent b8a32c2 commit 7bd2172

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

src/main/java/com/crossoverjie/algorithm/TwoSum.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.crossoverjie.algorithm;
22

3+
import java.util.HashMap;
4+
import java.util.Map;
5+
36
/**
47
* Function:
58
*
@@ -9,6 +12,12 @@
912
*/
1013
public 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
}

src/test/java/com/crossoverjie/algorithm/TwoSumTest.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff 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
}

0 commit comments

Comments
 (0)