📌  相关文章
📜  从两端交替重复删除每个第二个元素后找到最后一个元素

📅  最后修改于: 2021-10-26 06:58:38             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[] ,任务是从第一个和最后一个交替开始,每删除第二个元素后找到最后剩余的数组元素。

例子:

朴素的方法:解决这个问题的最简单的方法是从第一个和最后一个索引开始交替删除数组中的每个第二个元素,直到数组的大小减小到1 。执行给定操作后打印剩余的最后一个数组元素。

时间复杂度: O(N 2 )
辅助空间: O(1)

高效方法:上述方法也可以通过观察下图中的N = 20进行优化:

从上图可以得出以下观察结果:

  • 每次消除N/2 个数字。
  • 如果转弯方向是从左到右(→),则序列的第一个元素更改为(currentFirstElement + 2 step – 1 )
  • 如果转弯方向是从右到左(←),然后列表中的剩余数字为奇数,则序列的第一个元素更改为(currentFirstElement + 2 step – 1 )
  • 通过上述步骤得到currentFirstElement的最终值后,将该值打印为序列中的剩余元素。

脚步:

  • 初始化一个变量,比如leftTurn ,以检查元素是从左边还是右边删除。
  • 将变量retainElements初始化为Nsteps1head1 ,以存储序列中的剩余元素、执行的步骤数和序列的第一个元素。
  • 迭代直到剩余元素大于1
    • 如果leftTurn 的值为true ,则将头部更新为(head + 2 step – 1 ) 。否则,如果剩余元素为奇数,则将头部更新为(head + 2 step – 1 )
    • remainElement的值更新为remainElement/2
    • 步骤更新为2 * steps
    • 切换leftTurn以从右侧移除元素。
  • 完成上述步骤后,将索引(head – 1)处的值作为剩余元素打印。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the last element
// remaining in the array after
// performing the given operations
void printLastElement(int arr[], int N)
{
    // Checks if traversal is from
    // left to right or vice versa
    bool leftTurn = true;
 
    // Store the elements currently
    // present in the array
    int remainElements = N;
 
    // Store the distance between 2
    // consecutive array elements
    int step = 1;
 
    // Store the first element
    // of the remaining array
    int head = 1;
 
    // Iterate while elements
    // are greater than 1
    while (remainElements > 1) {
 
        // If left to right turn
        if (leftTurn) {
 
            // Update head
            head = head + step;
        }
 
        // Otherwise, check if the
        // remaining elements are odd
        else {
 
            // If true, update head
            if (remainElements % 2 == 1)
                head = head + step;
        }
 
        // Eleminate half of the array elements
        remainElements = remainElements / 2;
 
        // Double the steps after each turn
        step = step * 2;
 
        // Alter the turn
        leftTurn = !leftTurn;
    }
 
    // Print the remaining element
    cout << arr[head - 1];
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 3, 5, 6 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    printLastElement(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.lang.*;
 
class GFG{
 
// Function to find the last element
// remaining in the array after
// performing the given operations
public static void printLastElement(int arr[], int N)
{
     
    // Checks if traversal is from
    // left to right or vice versa
    boolean leftTurn = true;
 
    // Store the elements currently
    // present in the array
    int remainElements = N;
 
    // Store the distance between 2
    // consecutive array elements
    int step = 1;
 
    // Store the first element
    // of the remaining array
    int head = 1;
 
    // Iterate while elements
    // are greater than 1
    while (remainElements > 1)
    {
 
        // If left to right turn
        if (leftTurn)
        {
 
            // Update head
            head = head + step;
        }
 
        // Otherwise, check if the
        // remaining elements are odd
        else
        {
 
            // If true, update head
            if (remainElements % 2 == 1)
                head = head + step;
        }
 
        // Eleminate half of the array elements
        remainElements = remainElements / 2;
 
        // Double the steps after each turn
        step = step * 2;
 
        // Alter the turn
        leftTurn = !leftTurn;
    }
 
    // Print the remaining element
    System.out.print( arr[head - 1]);
}
 
// Driver code
public static void main(String args[])
{
    int[] arr = { 2, 3, 5, 6 };
    int N = arr.length;
     
    printLastElement(arr, N);
}
}
 
// This code is contributed by SoumikMondal


Python3
# Python3 program for the above approach
 
# Function to find the last element
# remaining in the array after
# performing the given operations
def printLastElement(arr, N):
 
    # Checks if traversal is from
    # left to right or vice versa
    leftTurn = True
 
    # Store the elements currently
    # present in the array
    remainElements = N
 
    # Store the distance between 2
    # consecutive array elements
    step = 1
 
    # Store the first element
    # of the remaining array
    head = 1
 
    # Iterate while elements
    # are greater than 1
    while (remainElements > 1):
 
        # If left to right turn
        if (leftTurn):
 
            # Update head
            head = head + step
 
        # Otherwise, check if the
        # remaining elements are odd
        else:
 
            # If true, update head
            if (remainElements % 2 == 1):
                head = head + step
 
        # Eleminate half of the array elements
        remainElements = remainElements // 2
 
        # Double the steps after each turn
        step = step * 2
 
        # Alter the turn
        leftTurn = not leftTurn
 
    # Print the remaining element
    print(arr[head - 1])
 
 
# Driver Code
if __name__ == "__main__":
 
    arr = [ 2, 3, 5, 6 ]
    N = len(arr)
 
    printLastElement(arr, N)
 
# This code is contributed by ukasp


Javascript


C#
// C# program for the above approach
using System;
 
public class GFG{
     
    // Function to find the last element
// remaining in the array after
// performing the given operations
public static void printLastElement(int[] arr, int N)
{
      
    // Checks if traversal is from
    // left to right or vice versa
    bool leftTurn = true;
  
    // Store the elements currently
    // present in the array
    int remainElements = N;
  
    // Store the distance between 2
    // consecutive array elements
    int step = 1;
  
    // Store the first element
    // of the remaining array
    int head = 1;
  
    // Iterate while elements
    // are greater than 1
    while (remainElements > 1)
    {
  
        // If left to right turn
        if (leftTurn)
        {
  
            // Update head
            head = head + step;
        }
  
        // Otherwise, check if the
        // remaining elements are odd
        else
        {
  
            // If true, update head
            if (remainElements % 2 == 1)
                head = head + step;
        }
  
        // Eleminate half of the array elements
        remainElements = remainElements / 2;
  
        // Double the steps after each turn
        step = step * 2;
  
        // Alter the turn
        leftTurn = !leftTurn;
    }
  
    // Print the remaining element
    Console.Write( arr[head - 1]);
}
  
// Driver code
     
    static public void Main (){
        int[] arr = { 2, 3, 5, 6 };
    int N = arr.Length;
      
    printLastElement(arr, N);
    }
     
}
 
// This code is contributed by avanitrachhadiya2155


输出:
3

时间复杂度: O(log N)
辅助空间: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程