和为S的两个数字(递增数列左右两个指针移动)

本文介绍了一种在已排序数组中寻找两数,使其和为特定值的方法,并提出了两种解决方案:一种利用二分查找,另一种使用双指针技巧。通过这两种高效算法,可以在O(n)时间内找到符合条件的数对。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。

输出描述:

对应每个测试案例,输出两个数,小的先输出。

(1)用和减去指定的一个数字,得到另一个数字,用二分查找看数列中存在这个数字

import java.util.ArrayList;
import java.util.Collections;
public class Solution {
    public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
        	ArrayList<Integer> list=new ArrayList<Integer>();
    	int one=0;int two=0;
    	for(int i=0;i<array.length;i++){
    		int another=sum-array[i];
    		int multi=Integer.MAX_VALUE;
	//		System.out.println("another"+another+" "+findOther(array,another,0,array.length));

    		if(findOther(array,another,0,array.length)){
    			if(multi>array[i]*another){			
    				multi=array[i]*another;
    				one=array[i];
    				two=another;
    			}
    		}
    	}
        if(one!=0&&two!=0){
    	list.add(one);
		list.add(two);
		Collections.sort(list);
    	}
        return list;
    }
    private static boolean findOther(int[] array, int another,int start,int end) {
		while(start<=end){
			int mid=start+(end-start)/2;
			if(array[mid]==another){
				return true;
			}else if(array[mid]<another){
				start=mid+1;
			}else{
				end=mid-1;
			}
		}
		return false;
	}
}


(2)递增数列,左右两个指针往中间移动

import java.util.ArrayList;
import java.util.Collections;
public class Solution {
    public ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
        ArrayList<Integer> list=new ArrayList<Integer>();
    	int one=0;int two=array.length-1;
    	while(one<two){
    		if(array[one]+array[two]==sum){
    			list.add(array[one]);
    			list.add(array[two]);
    			return list;
    		}else if(array[one]+array[two]<=sum){
    			one++;
    		}else{
    			two--;
    		}
    	}
    	return list;
	}
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值