关闭

leetcode

96人阅读 评论(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

猜你在找
【套餐】Hadoop生态系统零基础入门
【套餐】嵌入式Linux C编程基础
【套餐】2017软考系统集成项目——任铄
【套餐】Android 5.x顶级视频课程——李宁
【套餐】深度学习入门视频课程——唐宇迪
【直播】广义线性模型及其应用——李科
【直播】从0到1 区块链的概念到实践
【直播】计算机视觉原理及实战——屈教授
【直播】机器学习之凸优化——马博士
【直播】机器学习&数据挖掘7周实训--韦玮
查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:150次
    • 积分:30
    • 等级:
    • 排名:千里之外
    • 原创:3篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档