博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 167. Two Sum II - Input array is sorted
阅读量:5886 次
发布时间:2019-06-19

本文共 1605 字,大约阅读时间需要 5 分钟。

problem:

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 and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

 

 

first try:

class Solution {    public int[] twoSum(int[] numbers, int target) {        //find the first number samller than the target        int index2 =0;        for(int i=numbers.length-1; 0<=i;i--){            if(numbers[i]

result:

 

Submission Result: Runtime Error Runtime Error Message: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3    at Solution.twoSum(Solution.java:14)    at __Driver__.main(__Driver__.java:23)Last executed input: [2,3,4]6

又是数组越界。

 

second try:

class Solution {    public int[] twoSum(int[] numbers, int target) {        //find the first number samller than the target        int index2 =0;        for(int i=numbers.length-1; 0<=i;i--){            if(numbers[i]

 

result:

Submission Result: Wrong Answer Input: [-1,0]-1Output: [0,0]Expected: [1,2]

 

应考虑负数和0的情况。

third try:

class Solution {    public int[] twoSum(int[] numbers, int target) {        //two pointers        int index1 =0, index2 =numbers.length-1;                while(index1

 

result:

 

anylysis:

典型的双指针问题。

转载于:https://www.cnblogs.com/hzg1981/p/8926344.html

你可能感兴趣的文章
完整的删除
查看>>
红帽(Red Hat Linux)下SVN服务器的安装与配置
查看>>
RecyclerView使用介绍
查看>>
Java里面使用Date.compareTo比较时间
查看>>
dnsmasq一次成功的配置
查看>>
std::ios_base::fmtflags orig std::streamsize prec
查看>>
linux GUI程序开发
查看>>
C++ 静态链表基本算法实现
查看>>
工具类
查看>>
vue-webpack 引入echarts 注意事项
查看>>
指针的应用
查看>>
ORACLE 总结
查看>>
实战部署FAST Search Server 2010 for SharePoint (转闪电)
查看>>
二.Python基本数据类型
查看>>
python常用模块---转载
查看>>
web框架-(七)Django补充---models进阶操作及modelform操作
查看>>
kali访问宿主机Web页面解决方案
查看>>
html简介
查看>>
Android利用文本分割拼接开发一个花藤文字生成
查看>>
哈夫曼树的实现
查看>>