java - 两种不同算法的语句分析

标签 java time-complexity

我最近制作了一个自行车行程分析器,您可以在其中输入您的行驶距离和该行程的平均速度,它会计算您的时间,将您当前的速度与您的最小速度、最大速度和所有速度的平均速度进行排名输入迄今为止的数据,然后按速度、距离和时间绘制您的进度(最近 10 次行程)。事情一直按计划进行,除了我必须删除记录(当时是不正确的记录)并正常运行程序(由于数据库对索引所做的操作,编号全部搞砸了)。我添加了一个函数来帮助缓解一些问题,但它并没有完全解决问题。 (它不会准确显示 10 条记录,因为在指定的时间间隔内缺少一些记录编号。)所以现在,我正在改进它,并找到了两种方法来做到这一点。

我找到了一种简单的递归方法,以及相应的迭代方法。

<小时/>

递归方式:

private int calculateOffset(int min, int max)
{
    int actualTripNumber = 0, expectedTripNumber = 0, totalOffset = 0;
    try
    {
        resultSet = statement.executeQuery("SELECT TripNumber FROM BikeTripRecords WHERE TripNumber > " + 
            ((max == 0) ? String.format("(SELECT max(TripNumber) FROM BikeTripRecords) - %d", maxShowableRecords) : 
                String.format("%d AND TripNumber < %d", min, max))
            );
        //we could set expectedTripNumber = min + 1 (and then offset = min + 1), but that would cost one instruction
        while (resultSet.next())
        {
            actualTripNumber = resultSet.getInt(1);     //get the actualTripNumber
            totalOffset += ((expectedTripNumber > 0) ? actualTripNumber - expectedTripNumber : actualTripNumber - (min + 1));   //calculate the offset
            expectedTripNumber = actualTripNumber + 1;  //we expect the next actualTripNumber to be one more than the current one
        }
    }
    catch (SQLException exception)
    {
        exception.printStackTrace();
        return -1;  //You KNOW something went wrong with a negative return value; this could be replaced by System.exit(1), however
    }

    //conditional tail recursion; this should end with the last recursive call to return 0
    if (totalOffset > 0)
    {
        //if this function was called from the outside 
        if (max == 0)
        {
            //we assign to max the first number from the resultSet
            int newMax = resultSet.getInt(1);
            totalOffset += calculateOffset(newMax - totalOffset, newMax);
        }
        else
        {
            totalOffset += calculateOffset(min - totalOffset, min);
        }
    }
    return totalOffset;
}

迭代方式:

private int calculateOffset()
{
    //This version of calculateOffset() will be ITERATIVE, not recursive (and will use a helper function)
    int totalOffset = 0, intervalOffset = 1000; //giving intervalOffset a garbage value (so that we could use it in the while loop)
    int minimum = 0, maximum = 0;
    //this is the first calculation; we obtain the max(TripNumber) from BikeTripRecords (this method will only be called ONCE)
    try
    {
        resultSet = statement.executeQuery("SELECT max(TripNumber) FROM BikeTripRecords");
        resultSet.next();
        maximum = resultSet.getInt(1);  //fetching maximum
        minimum = maximum - maxShowableRecords;     //while we are at it, we might as well assign minimum a value here, too...
        }
    catch (SQLException exception)
    {
        exception.printStackTrace();
        return -1;  // You know something went wrong when the return value is negative!!
    }
    //we simply add to totalOffset the return value of our helper function (the offset of the intervals specified) while it doesn't return 0
    while (intervalOffset > 0)
    {
        intervalOffset = getIntervalOffset(minimum, maximum);   //get the intervalOffset
        totalOffset += intervalOffset;      //add it to the totalOffset
        //recalculate maximum, minimum
        maximum = minimum;
        minimum -= intervalOffset;
    }
    return totalOffset;
}

//helper function
private int getIntervalOffset (int min, int max)
{
    int offset = 0; //the value of this variable will be the return value (if everything goes according to plan)
    int actualTripNumber = 0, expectedTripNumber = 0;
    try
    {
        resultSet = statement.executeQuery(String.format("SELECT TripNumber FROM BikeTripRecords WHERE TripNumber > %d AND TripNumber <= %d", min, max));
        //computing the offset of the interval
        while (resultSet.next())
        {
            actualTripNumber = resultSet.getInt(1);     //getting the actualTripNumber
            //the only offset there should be the first time around should be the difference between the actualTripNumber and one more than the min
            //otherwise, the offset should be the difference between the actualTripNumber and the expectedTripNumber
            offset += ((expectedTripNumber > 0) ? actualTripNumber - expectedTripNumber : actualTripNumber - (min + 1));    
            expectedTripNumber = actualTripNumber + 1;  //the expectedTripNumber should be one more than the actualTripNumber
        }
    }
    catch (SQLException exception)
    {
        exception.printStackTrace();
        return -1;  // How you KNOW something went wrong....
    }
    return offset;
}

两个代码片段都检查 k 个间隔(k 是正整数)。让我困惑的是每种方法的算法复杂度的计算。两种方法的关键部分完全相同:一个 while 循环恰好执行 10-m 次(其中 m 是计算出的正在检查的时间间隔内丢失记录的数量)。在这里,我们可以肯定地说 m 的上限为 10。我对这两种方法得出的复杂度是关于 k 和 sum(mj, j 介于 1 和 k) 之间的线性关系,即 32k-(2+递归方式为 3 sum (mj, j Between 1 and k-1)) 和 4+31k-3 sum (mj, j Between 1 and k-1)。 (这里,mj 读作“m sub j”。)这两种算法的复杂度会被摊销还是会是 O(max{k, sum(mj, j between 1 and k-1)})?

最佳答案

为什么不让自己省去麻烦而直接获取 10 个最新结果呢?

由于您使用的是 Derby ,您可以通过以下方式限制结果:

statement.setMaxRows(10); 

然后,假设您的 TripNumber 列是一个自动递增的 ID,您只需对结果进行排序即可:

SELECT TripNumber FROM BikeTripRecords 
ORDER BY TripNumber DESC

关于java - 两种不同算法的语句分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17932207/

相关文章:

java - 如何在运行时从文件夹加载 jar 文件并在 JBoss EAP 6.0.1 中实例化类

java - 如何使用 GridLayout 或 GridBagLayout 垂直填充 JPanel?

algorithm - KMP算法最坏情况分析

algorithm - 如何解决这个递归关系: T(n) = T(n-1) * T(n-2)

algorithm - 递归树和渐近复杂性 : T(n) = T(n/3) + T(n/2) + n

java - Quartz 作业的 Cron 作业语法

java - hibernate 刷新方法

java - Java 中的 SecureRandom 安全种子

c++ - 为什么 O(NlogN) 算法所花费的时间与 O(N^2) 相同?

java - 简单 while 循环的时间复杂度