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

时间:2018-06-04 14:02:09

标签: 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}

在所有旋转之后,我们在给定的索引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));
        }
    }

这将给出正确的结果,但是后面会产生错误的结果。

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--;
                }
            }

2 个答案:

答案 0 :(得分:1)

Not Able to Understand Why starting from last rotation gives right result but if we start from rotation 0 to last in loop it gives wrong result???

Because its not supposed to give the same output. The final results depends on the order in which you apply the rotations.

Suppose first you apply {0,3}, the array would be :

4 , 1 , 2 , 3 , 5

Now you apply {0,2}

2 , 4 , 1 , 3 , 5

Clearly the element at index 1 is NOT 3

答案 1 :(得分:1)

让我们考虑给定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(根据逻辑)

希望这个解释能弄清楚为什么旋转数组要反向迭代。