📌  相关文章
📜  通过交换给定数组中偶数和奇数元素的位置来重新排列数组

📅  最后修改于: 2021-09-03 03:46:01             🧑  作者: Mango

给定一个由N 个正整数组成的数组arr[] ,具有相等数量的偶数和奇数元素。任务是使用就地交换来交换数组中偶数和奇数元素的位置。

例子:

朴素的方法:最简单的方法是使用两个循环遍历数组元素,外循环选取数组的每个元素,内循环为选取的元素找到相反的奇偶校验元素并交换它们。交换元素后,将选取的元素标记为负值,以免再次选取。最后,使所有元素为正并打印数组。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include
using namespace std;
 
// Function to replace each even
// element by odd and vice-versa
// in a given array
void replace(int arr[], int n)
{
     
    // Traverse array
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
             
            // If current element is even
            // then swap it with odd
            if (arr[i] >= 0 && arr[j] >= 0 &&
                arr[i] % 2 == 0 &&
                arr[j] % 2 != 0)
            {
                 
                // Perform Swap
                int tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
 
                // Change the sign
                arr[j] = -arr[j];
 
                break;
            }
 
            // If current element is odd
            // then swap it with even
            else if (arr[i] >= 0 && arr[j] >= 0 &&
                     arr[i] % 2 != 0 &&
                     arr[j] % 2 == 0)
            {
                 
                // Perform Swap
                int tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
 
                // Change the sign
                arr[j] = -arr[j];
 
                break;
            }
        }
    }
 
    // Marked element positive
    for(int i = 0; i < n; i++)
        arr[i] = abs(arr[i]);
 
    // Print final array
    for(int i = 0; i < n; i++)
         cout << arr[i] << " ";
}
 
// Driver Code
int main()
{
     
    // Given array arr[]
    int arr[] = { 1, 3, 2, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
     
    // Function Call
    replace(arr,n);
}
 
// This code is contributed by SURENDRA_GANGWAR


Java
// Java program for the above approach
import java.util.*;
import java.lang.*;
 
class GFG {
 
    // Function to replace each even
    // element by odd and vice-versa
    // in a given array
    static void replace(int[] arr)
    {
        // Stores length of array
        int n = arr.length;
 
        // Traverse array
        for (int i = 0; i < n; i++) {
 
            for (int j = i + 1; j < n; j++) {
 
                // If current element is even
                // then swap it with odd
                if (arr[i] >= 0
                    && arr[j] >= 0
                    && arr[i] % 2 == 0
                    && arr[j] % 2 != 0) {
 
                    // Perform Swap
                    int tmp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = tmp;
 
                    // Change the sign
                    arr[j] = -arr[j];
 
                    break;
                }
 
                // If current element is odd
                // then swap it with even
                else if (arr[i] >= 0
                         && arr[j] >= 0
                         && arr[i] % 2 != 0
                         && arr[j] % 2 == 0) {
 
                    // Perform Swap
                    int tmp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = tmp;
 
                    // Change the sign
                    arr[j] = -arr[j];
 
                    break;
                }
            }
        }
 
        // Marked element positive
        for (int i = 0; i < n; i++)
            arr[i] = Math.abs(arr[i]);
 
        // Print final array
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int[] arr = { 1, 3, 2, 4 };
 
        // Function Call
        replace(arr);
    }
}


Python3
# Python3 program for the
# above approach
 
# Function to replace each even
# element by odd and vice-versa
# in a given array
def replace(arr,  n):
 
    # Traverse array
    for i in range(n):
        for j in range(i + 1, n):
 
            # If current element is
            # even then swap it with odd
            if (arr[i] >= 0 and
                arr[j] >= 0 and
                arr[i] % 2 == 0 and
                arr[j] % 2 != 0):
 
                # Perform Swap
                tmp = arr[i]
                arr[i] = arr[j]
                arr[j] = tmp
 
                # Change the sign
                arr[j] = -arr[j]
 
                break
 
            # If current element is odd
            # then swap it with even
            elif (arr[i] >= 0 and
                  arr[j] >= 0 and
                  arr[i] % 2 != 0 and
                  arr[j] % 2 == 0):
 
                # Perform Swap
                tmp = arr[i]
                arr[i] = arr[j]
                arr[j] = tmp
 
                # Change the sign
                arr[j] = -arr[j]
 
                break
 
    # Marked element positive
    for i in range(n):
        arr[i] = abs(arr[i])
 
    # Print final array
    for i in range(n):
        print(arr[i], end = " ")
 
# Driver Code
if __name__ == "__main__":
 
    # Given array arr[]
    arr = [1, 3, 2, 4]
    n = len(arr)
 
    # Function Call
    replace(arr, n)
 
# This code is contributed by Chitranayal


C#
// C# program for the above approach
using System;
 
class GFG{
     
// Function to replace each even
// element by odd and vice-versa
// in a given array
static void replace(int[] arr)
{
     
    // Stores length of array
    int n = arr.Length;
 
    // Traverse array
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
             
            // If current element is even
            // then swap it with odd
            if (arr[i] >= 0 &&
                arr[j] >= 0 &&
                arr[i] % 2 == 0 &&
                arr[j] % 2 != 0)
            {
                 
                // Perform Swap
                int tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
                 
                // Change the sign
                arr[j] = -arr[j];
 
                break;
            }
 
            // If current element is odd
            // then swap it with even
            else if (arr[i] >= 0 &&
                     arr[j] >= 0 &&
                     arr[i] % 2 != 0 &&
                     arr[j] % 2 == 0)
            {
                 
                // Perform Swap
                int tmp = arr[i];
                arr[i] = arr[j];
                arr[j] = tmp;
                 
                // Change the sign
                arr[j] = -arr[j];
 
                break;
            }
        }
    }
 
    // Marked element positive
    for(int i = 0; i < n; i++)
        arr[i] = Math.Abs(arr[i]);
 
    // Print readonly array
    for(int i = 0; i < n; i++)
        Console.Write(arr[i] + " ");
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int[] arr = { 1, 3, 2, 4 };
 
    // Function Call
    replace(arr);
}
}
 
// This code is contributed by Rajput-Ji


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
#define N 3
#define M 4
 
// Function to replace odd elements
// with even elements and vice versa
void swapEvenOdd(int arr[], int n)
{
    int o = -1, e = -1;
 
    // Traverse the given array
    for(int i = 0; i < n; i++)
    {
         
        // If arr[i] is visited
        if (arr[i] < 0)
            continue;
 
        int r = -1;
 
        if (arr[i] % 2 == 0)
        {
            o++;
             
            // Find the next odd element
            while (arr[o] % 2 == 0 || arr[o] < 0)
                o++;
                 
            r = o;
        }
        else
        {
            e++;
             
            // Find next even element
            while (arr[e] % 2 == 1 || arr[e] < 0)
                e++;
                 
            r = e;
        }
 
        // Mark them visited
        arr[i] *= -1;
        arr[r] *= -1;
 
        // Swap them
        int tmp = arr[i];
        arr[i] = arr[r];
        arr[r] = tmp;
    }
 
    // Print the final array
    for(int i = 0; i < n; i++)
    {
        cout << (-1 * arr[i]) << " ";
    }
}
 
// Driver Code
int main()
{
     
    // Given array arr[]
    int arr[] = { 1, 3, 2, 4 };
     
    // Length of the array
    int n = sizeof(arr) / sizeof(arr[0]);
     
    // Function Call
    swapEvenOdd(arr, n);
}
 
// This code is contributed by Rajput-Ji


Java
// Java program for the above approach
 
import java.io.*;
 
class GFG {
 
    // Function to replace odd elements
    // with even elements and vice versa
    static void swapEvenOdd(int arr[])
    {
        // Length of the array
        int n = arr.length;
 
        int o = -1, e = -1;
 
        // Traverse the given array
        for (int i = 0; i < n; i++) {
 
            // If arr[i] is visited
            if (arr[i] < 0)
                continue;
 
            int r = -1;
 
            if (arr[i] % 2 == 0) {
                o++;
 
                // Find the next odd element
                while (arr[o] % 2 == 0
                       || arr[o] < 0)
                    o++;
                r = o;
            }
            else {
                e++;
 
                // Find next even element
                while (arr[e] % 2 == 1
                       || arr[e] < 0)
                    e++;
                r = e;
            }
 
            // Mark them visited
            arr[i] *= -1;
            arr[r] *= -1;
 
            // Swap them
            int tmp = arr[i];
            arr[i] = arr[r];
            arr[r] = tmp;
        }
 
        // Print the final array
        for (int i = 0; i < n; i++) {
            System.out.print(
                (-1 * arr[i]) + " ");
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int arr[] = { 1, 3, 2, 4 };
 
        // Function Call
        swapEvenOdd(arr);
    }
}


Python3
# Python3 program for the above approach
 
# Function to replace odd elements
# with even elements and vice versa
def swapEvenOdd(arr):
     
    # Length of the array
    n = len(arr)
 
    o = -1
    e = -1
 
    # Traverse the given array
    for i in range(n):
         
        # If arr[i] is visited
        if (arr[i] < 0):
            continue
 
        r = -1
 
        if (arr[i] % 2 == 0):
            o += 1
 
            # Find the next odd element
            while (arr[o] % 2 == 0 or
                   arr[o] < 0):
                o += 1
                 
            r = o
        else:
            e += 1
 
            # Find next even element
            while (arr[e] % 2 == 1 or
                   arr[e] < 0):
                e += 1
                 
            r = e
 
        # Mark them visited
        arr[i] *= -1
        arr[r] *= -1
 
        # Swap them
        tmp = arr[i]
        arr[i] = arr[r]
        arr[r] = tmp
 
    # Print the final array
    for i in range(n):
        print((-1 * arr[i]), end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    # Given array arr
    arr = [ 1, 3, 2, 4 ]
 
    # Function Call
    swapEvenOdd(arr)
 
# This code is contributed by Amit Katiyar


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function to replace odd elements
// with even elements and vice versa
static void swapEvenOdd(int []arr)
{
     
    // Length of the array
    int n = arr.Length;
 
    int o = -1, e = -1;
 
    // Traverse the given array
    for(int i = 0; i < n; i++)
    {
         
        // If arr[i] is visited
        if (arr[i] < 0)
            continue;
 
        int r = -1;
 
        if (arr[i] % 2 == 0)
        {
            o++;
             
            // Find the next odd element
            while (arr[o] % 2 == 0 ||
                   arr[o] < 0)
                o++;
                 
            r = o;
        }
        else
        {
            e++;
 
            // Find next even element
            while (arr[e] % 2 == 1 ||
                   arr[e] < 0)
                e++;
                 
            r = e;
        }
 
        // Mark them visited
        arr[i] *= -1;
        arr[r] *= -1;
 
        // Swap them
        int tmp = arr[i];
        arr[i] = arr[r];
        arr[r] = tmp;
    }
 
    // Print the readonly array
    for(int i = 0; i < n; i++)
    {
        Console.Write((-1 * arr[i]) + " ");
    }
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 1, 3, 2, 4 };
 
    // Function Call
    swapEvenOdd(arr);
}
}
 
// This code is contributed by Amit Katiyar


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to replace odd elements
// with even elements and vice versa
void swapEvenOdd(int arr[], int N)
{
  stack > stack;
 
  // Push the first element to stack
  stack.push({ 0, arr[0] });
 
  // iterate the array and swap even and odd
  for (int i = 1; i < N; i++)
  {
    if (!stack.empty())
    {
      if (arr[i] % 2 != stack.top().second % 2)
      {
 
        // pop and swap
        pair pop = stack.top();
        stack.pop();
 
        int index = pop.first, val = pop.second;
        arr[index] = arr[i];
        arr[i] = val;
      }
      else
        stack.push({ i, arr[i] });
    }
    else
      stack.push({ i, arr[i] });
  }
 
  // print the arr[]
  for (int i = 0; i < N; i++)
    cout << arr[i] << " ";
}
 
// Driven Program
int main()
{
 
  // Given array arr[]
  int arr[] = { 1, 3, 2, 4 };
 
  // Stores the length of array
  int N = sizeof(arr) / sizeof(arr[0]);
 
  // Function Call
  swapEvenOdd(arr, N);
  return 0;
}
 
// This code is contributed by Kingash.


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
  // Function to replace odd elements
  // with even elements and vice versa
  static void swapEvenOdd(int arr[], int N)
  {
 
    Stack stack = new Stack<>();
 
    // Push the first element to stack
    stack.push(new int[] { 0, arr[0] });
 
    // iterate the array and swap even and odd
    for (int i = 1; i < N; i++)
    {
      if (!stack.isEmpty())
      {
        if (arr[i] % 2 != stack.peek()[1] % 2)
        {
 
          // pop and swap
          int pop[] = stack.pop();
          int index = pop[0], val = pop[1];
          arr[index] = arr[i];
          arr[i] = val;
        }
        else
          stack.push(new int[] { i, arr[i] });
      }
      else
        stack.push(new int[] { i, arr[i] });
    }
 
    // print the arr[]
    for (int i = 0; i < N; i++)
      System.out.print(arr[i] + " ");
  }
 
  // Driver code
  public static void main(String[] args)
  {
 
    // Given array arr
    int arr[] = { 1, 3, 2, 4 };
 
    // length of the arr
    int N = arr.length;
 
    // Function Call
    swapEvenOdd(arr, N);
  }
}
 
// This code is contributed by Kingash.


Python3
# Python3 program for the above approach
 
# Function to replace odd elements
# with even elements and vice versa
def swapEvenOdd(arr):
    stack = []
     
    # Push the first element to stack
    stack.append((0, arr[0],))
     
    # iterate the array and swap even and odd
    for i in range(1, len(arr)):
        if stack:
            if arr[i]%2 != stack[-1][1]%2:
                #pop and swap
                index, val = stack.pop(-1)
                arr[index] = arr[i]
                arr[i] = val
            else:
                stack.append((i, arr[i],))
        else:
            stack.append((i, arr[i],))
    return arr
 
# Driver Code
if __name__ == '__main__':
     
    # Given array arr
    arr = [ 1, 3, 2, 4 ]
 
    # Function Call
    print(swapEvenOdd(arr))
 
# This code is contributed by Arunabha Choudhury


输出
2 4 1 3 

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

高效的方法:为了优化上述方法,思想是使用两个指针方法。通过拾取大于0的每个元素遍历数组并搜索大于0从当前索引到该阵列的端部的相反奇偶性元件更大。如果找到,交换元素并将它们与-1相乘。请按照以下步骤解决问题:

  • -1初始化变量eo ,这将分别存储当前找到的尚未被采用的偶数和奇数。
  • [0, N – 1]范围内遍历给定数组并执行以下操作:
    • 如果元素arr[i]大于0 ,则选择它。
    • 如果arr[i]是偶数,则将o + 1增加1并找到下一个尚未标记的奇数。通过将当前和找到的数字乘以-1并交换它们来标记它们。
    • 如果arr[i]是奇数,则将e + 1增加1并找到下一个尚未标记的偶数。通过将当前和找到的数字乘以-1并交换它们来标记它们。
  • 遍历整个数组后,将其元素乘以-1再次使它们为正数并打印该数组。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
#define N 3
#define M 4
 
// Function to replace odd elements
// with even elements and vice versa
void swapEvenOdd(int arr[], int n)
{
    int o = -1, e = -1;
 
    // Traverse the given array
    for(int i = 0; i < n; i++)
    {
         
        // If arr[i] is visited
        if (arr[i] < 0)
            continue;
 
        int r = -1;
 
        if (arr[i] % 2 == 0)
        {
            o++;
             
            // Find the next odd element
            while (arr[o] % 2 == 0 || arr[o] < 0)
                o++;
                 
            r = o;
        }
        else
        {
            e++;
             
            // Find next even element
            while (arr[e] % 2 == 1 || arr[e] < 0)
                e++;
                 
            r = e;
        }
 
        // Mark them visited
        arr[i] *= -1;
        arr[r] *= -1;
 
        // Swap them
        int tmp = arr[i];
        arr[i] = arr[r];
        arr[r] = tmp;
    }
 
    // Print the final array
    for(int i = 0; i < n; i++)
    {
        cout << (-1 * arr[i]) << " ";
    }
}
 
// Driver Code
int main()
{
     
    // Given array arr[]
    int arr[] = { 1, 3, 2, 4 };
     
    // Length of the array
    int n = sizeof(arr) / sizeof(arr[0]);
     
    // Function Call
    swapEvenOdd(arr, n);
}
 
// This code is contributed by Rajput-Ji

Java

// Java program for the above approach
 
import java.io.*;
 
class GFG {
 
    // Function to replace odd elements
    // with even elements and vice versa
    static void swapEvenOdd(int arr[])
    {
        // Length of the array
        int n = arr.length;
 
        int o = -1, e = -1;
 
        // Traverse the given array
        for (int i = 0; i < n; i++) {
 
            // If arr[i] is visited
            if (arr[i] < 0)
                continue;
 
            int r = -1;
 
            if (arr[i] % 2 == 0) {
                o++;
 
                // Find the next odd element
                while (arr[o] % 2 == 0
                       || arr[o] < 0)
                    o++;
                r = o;
            }
            else {
                e++;
 
                // Find next even element
                while (arr[e] % 2 == 1
                       || arr[e] < 0)
                    e++;
                r = e;
            }
 
            // Mark them visited
            arr[i] *= -1;
            arr[r] *= -1;
 
            // Swap them
            int tmp = arr[i];
            arr[i] = arr[r];
            arr[r] = tmp;
        }
 
        // Print the final array
        for (int i = 0; i < n; i++) {
            System.out.print(
                (-1 * arr[i]) + " ");
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int arr[] = { 1, 3, 2, 4 };
 
        // Function Call
        swapEvenOdd(arr);
    }
}

蟒蛇3

# Python3 program for the above approach
 
# Function to replace odd elements
# with even elements and vice versa
def swapEvenOdd(arr):
     
    # Length of the array
    n = len(arr)
 
    o = -1
    e = -1
 
    # Traverse the given array
    for i in range(n):
         
        # If arr[i] is visited
        if (arr[i] < 0):
            continue
 
        r = -1
 
        if (arr[i] % 2 == 0):
            o += 1
 
            # Find the next odd element
            while (arr[o] % 2 == 0 or
                   arr[o] < 0):
                o += 1
                 
            r = o
        else:
            e += 1
 
            # Find next even element
            while (arr[e] % 2 == 1 or
                   arr[e] < 0):
                e += 1
                 
            r = e
 
        # Mark them visited
        arr[i] *= -1
        arr[r] *= -1
 
        # Swap them
        tmp = arr[i]
        arr[i] = arr[r]
        arr[r] = tmp
 
    # Print the final array
    for i in range(n):
        print((-1 * arr[i]), end = " ")
 
# Driver Code
if __name__ == '__main__':
     
    # Given array arr
    arr = [ 1, 3, 2, 4 ]
 
    # Function Call
    swapEvenOdd(arr)
 
# This code is contributed by Amit Katiyar

C#

// C# program for the above approach
using System;
 
class GFG{
 
// Function to replace odd elements
// with even elements and vice versa
static void swapEvenOdd(int []arr)
{
     
    // Length of the array
    int n = arr.Length;
 
    int o = -1, e = -1;
 
    // Traverse the given array
    for(int i = 0; i < n; i++)
    {
         
        // If arr[i] is visited
        if (arr[i] < 0)
            continue;
 
        int r = -1;
 
        if (arr[i] % 2 == 0)
        {
            o++;
             
            // Find the next odd element
            while (arr[o] % 2 == 0 ||
                   arr[o] < 0)
                o++;
                 
            r = o;
        }
        else
        {
            e++;
 
            // Find next even element
            while (arr[e] % 2 == 1 ||
                   arr[e] < 0)
                e++;
                 
            r = e;
        }
 
        // Mark them visited
        arr[i] *= -1;
        arr[r] *= -1;
 
        // Swap them
        int tmp = arr[i];
        arr[i] = arr[r];
        arr[r] = tmp;
    }
 
    // Print the readonly array
    for(int i = 0; i < n; i++)
    {
        Console.Write((-1 * arr[i]) + " ");
    }
}
 
// Driver Code
public static void Main(String[] args)
{
     
    // Given array []arr
    int []arr = { 1, 3, 2, 4 };
 
    // Function Call
    swapEvenOdd(arr);
}
}
 
// This code is contributed by Amit Katiyar

Javascript


输出
2 4 1 3 

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

有效方法2:

另一种方法是使用堆栈。请按照以下步骤操作:

  1. 从数组 arr[] 中取出索引处的元素并压入堆栈
  2. 将 arr[] 从索引 i = 1 迭代到 end 并执行以下操作:
    1. 如果堆栈顶部的 arr[i] 和 item 不是偶数或不是奇数,则弹出和交换
    2. 否则将项目推入堆栈

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to replace odd elements
// with even elements and vice versa
void swapEvenOdd(int arr[], int N)
{
  stack > stack;
 
  // Push the first element to stack
  stack.push({ 0, arr[0] });
 
  // iterate the array and swap even and odd
  for (int i = 1; i < N; i++)
  {
    if (!stack.empty())
    {
      if (arr[i] % 2 != stack.top().second % 2)
      {
 
        // pop and swap
        pair pop = stack.top();
        stack.pop();
 
        int index = pop.first, val = pop.second;
        arr[index] = arr[i];
        arr[i] = val;
      }
      else
        stack.push({ i, arr[i] });
    }
    else
      stack.push({ i, arr[i] });
  }
 
  // print the arr[]
  for (int i = 0; i < N; i++)
    cout << arr[i] << " ";
}
 
// Driven Program
int main()
{
 
  // Given array arr[]
  int arr[] = { 1, 3, 2, 4 };
 
  // Stores the length of array
  int N = sizeof(arr) / sizeof(arr[0]);
 
  // Function Call
  swapEvenOdd(arr, N);
  return 0;
}
 
// This code is contributed by Kingash.

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
  // Function to replace odd elements
  // with even elements and vice versa
  static void swapEvenOdd(int arr[], int N)
  {
 
    Stack stack = new Stack<>();
 
    // Push the first element to stack
    stack.push(new int[] { 0, arr[0] });
 
    // iterate the array and swap even and odd
    for (int i = 1; i < N; i++)
    {
      if (!stack.isEmpty())
      {
        if (arr[i] % 2 != stack.peek()[1] % 2)
        {
 
          // pop and swap
          int pop[] = stack.pop();
          int index = pop[0], val = pop[1];
          arr[index] = arr[i];
          arr[i] = val;
        }
        else
          stack.push(new int[] { i, arr[i] });
      }
      else
        stack.push(new int[] { i, arr[i] });
    }
 
    // print the arr[]
    for (int i = 0; i < N; i++)
      System.out.print(arr[i] + " ");
  }
 
  // Driver code
  public static void main(String[] args)
  {
 
    // Given array arr
    int arr[] = { 1, 3, 2, 4 };
 
    // length of the arr
    int N = arr.length;
 
    // Function Call
    swapEvenOdd(arr, N);
  }
}
 
// This code is contributed by Kingash.

蟒蛇3

# Python3 program for the above approach
 
# Function to replace odd elements
# with even elements and vice versa
def swapEvenOdd(arr):
    stack = []
     
    # Push the first element to stack
    stack.append((0, arr[0],))
     
    # iterate the array and swap even and odd
    for i in range(1, len(arr)):
        if stack:
            if arr[i]%2 != stack[-1][1]%2:
                #pop and swap
                index, val = stack.pop(-1)
                arr[index] = arr[i]
                arr[i] = val
            else:
                stack.append((i, arr[i],))
        else:
            stack.append((i, arr[i],))
    return arr
 
# Driver Code
if __name__ == '__main__':
     
    # Given array arr
    arr = [ 1, 3, 2, 4 ]
 
    # Function Call
    print(swapEvenOdd(arr))
 
# This code is contributed by Arunabha Choudhury
输出
[4, 2, 3, 1]

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live