给定一个整形数组,是否能找出其中的两个数使其和为某个指定的值?

来源:互联网 发布:网络经营许可认证中心 编辑:程序博客网 时间:2024/05/17 17:17

输入数组为{1,5,7,3}以及指定的目标值为10,我们可以从中找出两个数3和7,和为10.

package chatpter6;


import java.util.Arrays;


public class num1 {

boolean hasSum(int[] A,int target){
boolean res = false;
Arrays.sort(A);
int i = 0,j = A.length-1;
while(i<j){
if(A[i] + A[j] == target){
res = true;
return res;
}else if(A[i] + A[j] < target){
i++;
}else if(A[i] + A[j] > target){
j--;
}
}
return res;

}

public static void main(String[] args) {
int[] A ={1,5,7,3};
int target = 10;
boolean res = new num1().hasSum(A, target);
System.out.println(res);
}
}

0 0
原创粉丝点击