0
点赞
收藏
分享

微信扫一扫

java面试题之求解两数之和

米小格儿 2022-04-19 阅读 62
java后端

java面试题之求解两数之和

要求: 给定一个整数和一个唯一数组,能否找到数组中的两个数使得其和等于该整数的值

举例:

输入数组: 1 5 7 3 
输入值:10
找到:3+7=10

解题思路:
可以尝试将该数组排序,然后从首尾移动,一次移动一端的指针,直到相遇或者找到答案为止.

代码:

package java_stu;
import java.util.Arrays;
import java.util.Scanner;

/**
 * @Description:
 * @Author: Zoutao
 * @Date: 2018/7/6
 * 输入:一个数组+一个指定数字
 * 输出:该数组中的两个数等于该值
 */
public class atguigu2 {
  public static void main(String [] args){
        Scanner red =new Scanner(System.in);
        int [] A = new int [4];

        for (int i = 0; i < 4; i++) {
            A[i]= red.nextInt();
        }
        int t =red.nextInt();
        atguigu2 zt =new atguigu2();
        boolean bool = zt.towSum(A,t);
        System.out.println(bool);
    }
   boolean towSum (int []A,int t){
        boolean res =false;
        if (A==null || A.length<2)
            return res;
        Arrays.sort(A);
        int i=0;
        int j=A.length-1;  //定义首尾指针
        while (i<j){
            if (A[i]+A[j]==t){
                res = true;
                System.out.println("找到的两个数字为:"+A[i]+"+"+A[j]+"="+t);
                break;
            }else if (A[i]+A[j]>t){
                j--;
                break;
            }else{
                i++;
            }
        }
       return res;
   }
}

运行结果:

这里写图片描述


举报

相关推荐

0 条评论