Skip to content

Commit 8575e8c

Browse files
committed
leetcode Problem 01 first try
1 parent 3a0fbe3 commit 8575e8c

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

java8/src/main/java/com/shekhargulati/leetcode/Problem01.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,29 @@ public static int[] twoSum(int[] numbers, int target) {
4343
return new int[0];
4444
}
4545

46+
/*
47+
Assume array is sorted then you can do it O(n)
48+
*/
49+
public static int[] twoSum_binarySearch(int[] numbers, int target) {
50+
/*
51+
Algorithm:
52+
1. Iterate over all the numbers and find the second number by subtracting the first from target
53+
2. Find the second number from the sorted array.
54+
3. If second number is found then return index of first and second and second else move to the next number.
55+
*/
56+
for (int i = 0; i < numbers.length; i++) {
57+
int first = numbers[0];
58+
if (first < target) {
59+
int second = target - first;
60+
int secondElementIndex = Arrays.binarySearch(numbers, second);
61+
if (secondElementIndex >= 0) {
62+
return new int[]{i, secondElementIndex};
63+
}
64+
}
65+
}
66+
return new int[0];
67+
}
68+
4669

4770
/*
4871
This solution in O(n^2)

java8/src/test/java/com/shekhargulati/leetcode/Problem01Test.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,16 @@ public void shouldWorkOnARandomArray() throws Exception {
3535
assertThat(pairs.length, equalTo(2));
3636

3737
}
38+
39+
@Test
40+
public void shouldFindTwoNumberWhoseSumIsEqualToTarget_sorted_binarySearch() throws Exception {
41+
int[] pairs = Problem01.twoSum_binarySearch(new int[]{2, 7, 11, 15}, 9);
42+
assertTrue(Arrays.equals(pairs, new int[]{0, 1}));
43+
}
44+
45+
@Test
46+
public void shouldReturnEmptyArrayWhenNoTwoElementsInTheArrayHaveSum_sorted_binarySearch() throws Exception {
47+
int[] pairs = Problem01.twoSum_binarySearch(new int[]{2, 7, 11, 15}, 12);
48+
assertTrue(Arrays.equals(pairs, new int[0]));
49+
}
3850
}

0 commit comments

Comments
 (0)