在多次旋转后查找给定索引处的元素

San*_*ani 4 java algorithm data-structures

Input : arr[] : {1, 2, 3, 4, 5}
        ranges[] = { {0, 2}, {0, 3} }
        index : 1
Output : 3
Explanation : After first given rotation {0, 2}
                arr[] = {3, 1, 2, 4, 5}
              After second rotation {0, 3} 
                arr[] = {4, 3, 1, 2, 5}
Run Code Online (Sandbox Code Playgroud)

在所有旋转之后,我们在给定的索引 1 处有元素 3。

无法理解为什么从最后一次旋转开始会给出正确的结果,但是如果我们从旋转 0 开始到循环中的最后一次,它会给出错误的结果???

https://www.geeksforgeeks.org/find-element-given-index-number-rotations/

// 旋转数组的 Java 代码 // 并回答索引查询

 import java.util.*;

    class GFG
    {
        // Function to compute the element at
        // given index
        static int findElement(int[] arr, int[][] ranges,
                                int rotations, int index)
        {
            for (int i = rotations - 1; i >= 0; i--) {

                // Range[left...right]
                int left = ranges[i][0];
                int right = ranges[i][1];

                // Rotation will not have any effect
                if (left <= index && right >= index) {
                    if (index == left)
                        index = right;
                    else
                        index--;
                }
            }

            // Returning new element
            return arr[index];
        }

        // Driver
        public static void main (String[] args) {
            int[] arr = { 1, 2, 3, 4, 5 };

            // No. of rotations
            int rotations = 2;

            // Ranges according to 0-based indexing
            int[][] ranges = { { 0, 2 }, { 0, 3 } };

            int index = 1;
            System.out.println(findElement(arr, ranges,
                                     rotations, index));
        }
    }
Run Code Online (Sandbox Code Playgroud)

这将给出正确的结果,但以下将产生错误的结果。

for (int i = 0; i < rotations; i++) {

                // Range[left...right]
                int left = ranges[i][0];
                int right = ranges[i][1];

                // Rotation will not have any effect
                if (left <= index && right >= index) {
                    if (index == left)
                        index = right;
                    else
                        index--;
                }
            }
Run Code Online (Sandbox Code Playgroud)

小智 7

让我们考虑给定 5 个长度的数组 A1。

您已在 A1 上应用了 {0,2} 轮换。改为A2。
您已在 A2 上应用了 {0,3} 旋转。它已更改为 A3

现在您正在A3中查找输出索引 1(在 A2 上旋转了 {0,3})。
因此,A3 中的索引 1 = A2 中的索引 0(根据逻辑)

现在您正在 A2 中查找索引 0(在 A1 上旋转 {0,2})
所以 A2 中的索引 0 = A1 中的索引 2(根据逻辑)逻辑)

希望这个解释清楚为什么旋转数组以相反的方式迭代。