【问题标题】:To minimizing the sum of two distances from the number最小化两个距离的总和
【发布时间】:2015-10-25 15:49:37
【问题描述】:

我有作业。作业是这样的

有数字X,以及数据类型为int的数组A和数组B。我应该找到最接近 X 的 A[I]+B[J](0

首先,我试图通过测试 All 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);
}

【问题讨论】:

  • 都是正数吗?时间限制和内存限制是多少?
  • 你能发布你当前的代码吗?
  • 我们需要查看您的算法,以确定什么会更好或更差。
  • 数组排序了吗?
  • 数字有正有负。它们没有排序。时间限制为 1s,内存限制为 128mb。我用代码编辑了我的问题。

标签: java algorithm minimization


【解决方案1】:

如果对数组进行排序,则可以使用修改后的 binary search 跟踪距离。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-25
    • 2019-01-26
    • 2017-11-07
    • 1970-01-01
    • 2011-04-06
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多