leetcode
来源:互联网 发布:php 公众号开发源码 编辑:程序博客网 时间:2024/04/29 11:51
刚开始写leetcode, 欢迎指正
题目描述如下:
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
设置两个收尾指针向中间移,如果大于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]);
}
}
}
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- SVN和Git的比较
- 蓝鸥Unity开发基础——析构方法
- zookeeper原理
- 160.Find the Difference
- iOS下的DES加密
- leetcode
- nginx grok 正则错误的输出情况
- 超级表格企业版:服务上万家中小企业,提升效率
- ORACLE客户端乱码--修改Oracle客户端字符集
- SIGCLD信号及配合wait的使用
- ListView-SimpleAdaptor
- POJ 2374 Fence Obstacle Course 线段树优化DP
- 浅谈Java中的equals和==
- Hexo在Github中搭建博客系统(3)Hexo安装主题