leetcode

来源:互联网 发布:php 公众号开发源码 编辑:程序博客网 时间:2024/04/29 11:51

刚开始写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
原创粉丝点击