(Algorithm - Double Pointer) The target sum of the array elements

(Algorithm - Double Pointer) The target sum of the array elements

Topic description

Given two sorted arrays A and B in ascending order, and a target value x.

Array subscripts start at 0.

Please find the pair (i,j) that satisfies A[i]+B[j]=x.

The data is guaranteed to have a unique solution.

Input format
The first line contains three integers n, m, x, which represent the length of A, the length of B and the target value x respectively.

The second line contains n integers representing array A.

The third line contains m integers representing array B.

Output format
One line containing two integers i and j.

Data range
The length of the array does not exceed 10 5 .
Elements within the same array are different.
1≤array element≤10 9Input example
:

4 5 6
1 2 4 7
3 4 6 8 9

Sample output:

1 1

topic analysis

1. Violent solution
for(i=0;i<n;i++){ for(j=0;j<m;j++){ if(A[i]+B[j]=x) output the answer (i, j) } Time complexity (O(n*m))=O(n^2) 2. Double pointer first find monotonicity A[i]+B[j]=x is fixed when A[i] increases When , B[j] must decrease, so we have









insert image description here

for(i=0,j=m-1;i<n;i++){
    
    
	while(j>=0 && A[i]+B[j]>x) j- -;
}

Time complexity O(n+m)=O(n)

solution

import java.util.Scanner;

public class Main {
    
    
	static int N=100010,n,m,x;
	static int[] a = new int[N];
	static int[] b = new int[N];
	
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		n= sc.nextInt();
		m= sc.nextInt();
		x= sc.nextInt();
		
		for(int i=0;i<n;i++) a[i] = sc.nextInt();
		for(int i=0;i<m;i++) b[i] = sc.nextInt();
		
		for(int i=0,j=m-1;i<n;i++) {
    
    
			while(j>=0 && a[i]+b[j]>x) j--;
			if(a[i]+b[j] == x) {
    
    
				System.out.println(i+" "+j);
				break;
			}
		}
	}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324130792&siteId=291194637