# leetcode

234人阅读 评论(0)

### 167. Two Sum II - Input array is sorted

• Total Accepted: 19291
• Total Submissions: 39203
• Difficulty: Medium

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.

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.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

import java.util.Scanner;

public class Solution {
public static int[] twoSum(int[] numbers, int target) {
int len = numbers.length;
int[] a = new int[2];

for(int i = 0,j = len - 1;i <len && j >i; )
{
if(numbers[i] + numbers[j] == target)
{
a[0] = i;
a[1] = j;
return a;
}
else if(numbers[i] + numbers[j] >target)
{
j--;
}
else
i++;
}

return a;
}
public static void main(String args[])
{
Scanner n = new Scanner(System.in);
String num =n.nextLine();
String[] pa = num.split(",");
int[] a = new int[pa.length];
for(int i = 0; i < pa.length; i ++)
a[i] = Integer.parseInt(pa[i]);
int target = n.nextInt();
int[] result = twoSum(a, target);
if(result != null)
{
for(int i = 0; i <2; i ++)
System.out.print(result[i]);
}

}

}

个人资料
等级：
访问量： 574
积分： 34
排名： 193万+
文章分类
文章存档