|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -import com.fishercoder.common.utils.CommonUtils; |
4 |
| - |
5 | 3 | /**
|
6 | 4 | * 167. Two Sum II - Input array is sorted
|
7 | 5 | *
|
8 |
| - * Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. |
9 |
| -
|
10 |
| - The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. |
11 |
| -
|
12 |
| - You may assume that each input would have exactly one solution. |
| 6 | + * Given an array of integers that is already sorted in ascending order, |
| 7 | + * find two numbers such that they add up to a specific target number. |
| 8 | + * The function twoSum should return indices of the two numbers such that they add up to the target, |
| 9 | + * where index1 must be less than index2. |
| 10 | + * Please note that your returned answers (both index1 and index2) are not zero-based. |
| 11 | + * You may assume that each input would have exactly one solution. |
13 | 12 |
|
14 | 13 | Input: numbers={2, 7, 11, 15}, target=9
|
15 | 14 | Output: index1=1, index2=2
|
16 |
| -
|
17 | 15 | */
|
| 16 | + |
18 | 17 | public class _167 {
|
19 |
| - public static int[] twoSum(int[] numbers, int target) { |
20 |
| - int left = 0, right = numbers.length-1; |
| 18 | + |
| 19 | + public int[] twoSum(int[] numbers, int target) { |
| 20 | + int left = 0, right = numbers.length - 1; |
21 | 21 | int[] result = new int[2];
|
22 |
| - while(numbers[right] > target) right--; |
23 |
| - if(right < numbers.length-1) right++; |
24 |
| - while(left <= right){ |
| 22 | + while (numbers[right] > target) { |
| 23 | + right--; |
| 24 | + } |
| 25 | + if (right < numbers.length - 1) { |
| 26 | + right++; |
| 27 | + } |
| 28 | + while (left <= right) { |
25 | 29 | int sum = numbers[left] + numbers[right];
|
26 |
| - if(sum > target) right--; |
27 |
| - else if(sum < target) left++; |
28 |
| - else if(sum == target){ |
29 |
| - result[0] = left+1; |
30 |
| - result[1] = right+1; |
| 30 | + if (sum > target) { |
| 31 | + right--; |
| 32 | + } else if (sum < target) { |
| 33 | + left++; |
| 34 | + } else if (sum == target) { |
| 35 | + result[0] = left + 1; |
| 36 | + result[1] = right + 1; |
31 | 37 | break;
|
32 | 38 | }
|
33 | 39 | }
|
34 | 40 | return result;
|
35 | 41 | }
|
36 |
| - |
37 |
| - public static void main(String...strings){ |
38 |
| - int[] nums = new int[]{-3,3,4,90}; |
39 |
| - int k = 0; |
40 |
| - int[] result = twoSum(nums, k); |
41 |
| - CommonUtils.printArray(result); |
42 |
| - } |
| 42 | + |
43 | 43 | }
|
0 commit comments