Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 试图通过旋转查询而不是数组来解决旋转数组查询_Java_Algorithm - Fatal编程技术网

Java 试图通过旋转查询而不是数组来解决旋转数组查询

Java 试图通过旋转查询而不是数组来解决旋转数组查询,java,algorithm,Java,Algorithm,输入: 前三个分别定义数组中的元素数、到数组的旋转数以及将在该数组上进行的查询数 第二个三是由数组组成的数字 最后三个是对数组进行的查询,其中array[query]应该是输出 这是我的代码: > publicstaticvoidmain(字符串[]args){ 扫描仪输入=新扫描仪(系统输入); int numberrelations=in.nextInt(); int numberRotations=in.nextInt(); int numberQuerys=in.nextInt(); i

输入:

前三个分别定义数组中的元素数、到数组的旋转数以及将在该数组上进行的查询数

第二个三是由数组组成的数字

最后三个是对数组进行的查询,其中array[query]应该是输出

这是我的代码:

>

publicstaticvoidmain(字符串[]args){
扫描仪输入=新扫描仪(系统输入);
int numberrelations=in.nextInt();
int numberRotations=in.nextInt();
int numberQuerys=in.nextInt();
int[]a=新的int[numberrelations];
for(int a_i=0;a_i

为什么我对大输入有问题?

您之所以有问题,是因为当
indexQuery
达到
numberRotations
时,您将其包装回零,但当它达到
numberrelations
(递增后)时,您应该进行包装,这是数组的大小。如果不是,则如果
numberRotations
大于
numberrelations
,则可以从数组末尾读取

另一个问题是,您应该从0开始计算
rotateQuery
,否则您将执行比您希望的少一次的旋转,因为循环只要小于
numberRotations
且不小于或等于,就会运行。您可以使用调试器进行验证,我建议您这样做

更有效的方法是将
numberRotations
添加到索引中,并使用模运算符处理换行,而不是循环:

indexQuery = (indexQuery + numberRotations) % numberElements;

这假设
numberRotations
为正,因此您可能也应该为此添加输入验证检查。

正如@samgak所说,您的算法似乎存在缺陷: 更改输入并使其旋转一次,输入为:

3 1 3 1 2 3 0 1 2
输出应为:

3 1 2
和你的输出

1 2 3
另一种解决方案是替换为循环:

for(int rotateQuery = 1; rotateQuery < numberRotations; rotateQuery++){
        if(indexQuery == numberRotations){
            indexQuery = 0;
        }
        else{
            indexQuery++;
        }
    }

因为rotate查询与rotate数组元素相反,所以我们应该减去numberRotations,而不是添加它。

“为什么我对大输入有问题?”这应该是对问题的描述吗?“有问题”不是问题描述。解释您的问题,例如显示输入、实际输出和预期输出。那样我们也许能帮上忙。对不起,安德烈亚斯。我不熟悉堆栈溢出和问题的预期格式。该查询的预期输出是:2 3 1所以我听取了大家的一些建议,并得出了以下结论:for(int a_i=0;a_i1 2 3
for(int rotateQuery = 1; rotateQuery < numberRotations; rotateQuery++){
        if(indexQuery == numberRotations){
            indexQuery = 0;
        }
        else{
            indexQuery++;
        }
    }
indexQuery = (indexQuery - numberRotations%numberElements+ numberElements) % numberElements;