Skip to content

Commit c594cd5

Browse files
author
Victor An
committed
add test case and input validation
1 parent b37dd50 commit c594cd5

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/solutions/P0001_Two_Sum.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,39 @@
2626
//. space: O(n) // merge sort, O(logn) quick sort
2727
// 3. hashmap to cache the seen num:index [key: num, value: index], lookup the target - nums[i] in the map, if found return the {map[target-nums[i]], i}
2828
//. O(n), O(n)
29+
30+
31+
// test case
32+
33+
// [1,2,3,1], 5 => [1,2]
34+
// [1,2,3,1], 2 => [0,3]
35+
// [0], 1 => throw IllegalArgumentException
36+
// null, 1 => throw IllegalArgumentException
37+
38+
class TwoSumTest {
39+
40+
void should_throw_IllegalArgumentException_when_nums_is_null() {
41+
42+
}
43+
44+
void should_throw_IllegalArgumentException_when_nums_has_less_than_2_elements() {
45+
46+
}
47+
48+
void should_return_expected_result() {
49+
50+
}
51+
}
52+
53+
2954
public class P0001_Two_Sum {
3055

3156
public int[] twoSum(int[] nums, int target) {
57+
// input validation
58+
if (nums == null || nums.length < 2) {
59+
throw new IllegalArgumentException("Invalid nums, which is not allowed be null and has more than 2 elements.");
60+
}
61+
3262
// 首先构建一个哈希表,用来存放数组的元素值以及索引值
3363
// 其中 key 是数组中的元素值
3464
// value 为数组中元素值的索引

0 commit comments

Comments
 (0)