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异常。

总结:

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

你可能感兴趣的:(LeetCode,死循环,TwoSum)