Skip to content

Commit d0b126f

Browse files
two sum II input array is sorted
1 parent 5d5b125 commit d0b126f

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package medium;
2+
3+
import utils.CommonUtils;
4+
5+
public class TwoSumIIInputArrayIsSorted {
6+
public static int[] twoSum(int[] numbers, int target) {
7+
int left = 0, right = numbers.length-1;
8+
int[] result = new int[2];
9+
while(numbers[right] > target) right--;
10+
if(right < numbers.length-1) right++;
11+
while(left <= right){
12+
int sum = numbers[left] + numbers[right];
13+
if(sum > target) right--;
14+
else if(sum < target) left++;
15+
else if(sum == target){
16+
result[0] = left+1;
17+
result[1] = right+1;
18+
break;
19+
}
20+
}
21+
return result;
22+
}
23+
24+
public static void main(String...strings){
25+
int[] nums = new int[]{-3,3,4,90};
26+
int k = 0;
27+
int[] result = twoSum(nums, k);
28+
CommonUtils.printArray(result);
29+
}
30+
}

0 commit comments

Comments
 (0)