2015-10-25 129 views
0

兩個距離的總和,我有作業。作業是這樣的爲了最大限度地減少距離數字

有數字X,數組類型爲int的數組A和數組B.我應該找到A [1] + B [J](0 < = I < =則爲a.length,0 < = j的< = b.length個),其是最接近X.

首先,我試圖通過測試找到答案全部I & J.但有時間限制和內存限制。所以我做了一個假設,大於X的數字是不需要的。但是,我面臨的時間限制再次出現問題。我如何節省時間?

我的代碼是這樣的。

import java.util.Scanner; 
import java.lang.Math; 

public class PRO_D{ 
public static void main(String[] args) 
{ 
    Scanner kb=new Scanner(System.in); 
    int aLen=kb.nextInt(); 
    int bLen=kb.nextInt(); 
    long number=kb.nextLong(); 
    long distance=100; 
    long dist=100; 
    int aCnt=0, bCnt=0; 
    long temp; 

    kb.nextLine(); 

    long[] arrA=new long[aLen]; 
    long[] arrB=new long[bLen]; 

    for(int i=0; i<aLen; i++) 
    { 
     temp = kb.nextLong(); 
     if (temp <= number) 
     { 
      if(number-temp<distance) 
      { 
       distance=number-temp; 
      } 
      arrA[i] = temp; 
      aCnt++; 
     } 
     else if(number-temp<distance) 
     { 
      arrA[i]=temp; 
      aCnt++; 
     } 
    } 

    for(int i=0; i<bLen; i++) 
    { 
     temp = kb.nextLong(); 
     if (temp <= number) 
     { 
      if(number-temp<distance) 
      { 
       distance=number-temp; 
      } 
      arrB[i] = temp; 
      bCnt++; 
     } 
     else if(number-temp<distance) 
     { 
      arrB[i]=temp; 
      bCnt++; 
     } 
    } 

    for(int i=0; i<aCnt; i++) 
     for(int j=0; j<bCnt; j++) 
     { 
      temp=Math.abs(number-arrA[i]-arrB[j]); 
      if(dist>temp) 
       dist=temp; 
     } 
    System.out.println(dist); 
} 
+0

他們都是正數嗎?什麼是時間限制和內存限制? – Bon

+0

你可以發佈你的當前代碼嗎? – Nick

+0

我們需要查看您的算法,以確定哪些更好或更糟。 – somecbusnerd

回答

0

如果對數組進行排序,修改後的binary search可以用於跟蹤距離的工作。

相關問題