关闭

leetcode

105人阅读 评论(0) 收藏 举报
分类:

刚开始写leetcode, 欢迎指正

题目描述如下:

167. Two Sum II - Input array is sorted

 
 My Submissions
  • 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


设置两个收尾指针向中间移,如果大于target,说明后边的比较大,左移,小于target,说明左边的比较小,右移,代码及测试代码如下:

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]);
}
 
}
       
   }


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:187次
    • 积分:31
    • 等级:
    • 排名:千里之外
    • 原创:3篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档