1 TwoSum

与之类似的题目有
15 3Sum
16 3Sum Closest
18 4Sum

LeetCode上的第一题Two Sum:

Given an array of integers, 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
    原题链接

第一次写的代码:

import java.util.Scanner;
import java.util.*;

public class TwoSum {

    public static void main(String[]args){

        Scanner scanner=new Scanner(System.in);

        ArrayList<Integer>input=new ArrayList<Integer>();

        while(scanner.hasNext()){
            int i=scanner.nextInt();
            input.add(i);           
        }

        //size()表示大小
        System.out.print(input.size()+",");
        //输出输入的数
        for(int j=0;j<input.size();j++){
            System.out.print(input.get(j)+",");
        }
        System.out.println();
    }
}

这段代码始终没有输出,原因是while循环没有终止条件,程序一直在等待接收键盘数据,造成死循环。

后将代码改成:

import java.util.Scanner;
import java.util.*;

public class TwoSum {

    public static void main(String[]args){

        Scanner scanner=new Scanner(System.in);

        ArrayList<Integer>input=new ArrayList<Integer>();

        while(scanner.hasNext()){
            int i=scanner.nextInt();
            input.add(i);

            for(int j=0;j<input.size()-1;j++)
                for(int m=j+1;m<input.size()-2;m++){
                    if(input.get(input.size()-1)==(input.get(m)+input.get(j)))
                        System.out.println("index1="+(j+1)+",index2="+(m+1));
                }

//          //size()表示大小
//          System.out.print(input.size()+",");
//          //输出输入的数
//          for(int j=0;j<input.size();j++){
//              System.out.print(input.get(j)+",");
//          }
//          System.out.println();
        }
    }
}

将输出语句移到while循环内。
这样有一个坏处就是程序始终处于运行状态,除非手动终止。
只能接收Integer,如果输入非Integer数据就会产生java.util.InputMismatchException异常。

总结:

在循环中最好有终止条件,否则始终无法跳出循环。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值