📌  相关文章
📜  将所有负数移到开头,将正数移到结尾,并留有恒定的额外空间

📅  最后修改于: 2022-05-13 01:57:52.098000             🧑  作者: Mango

将所有负数移到开头,将正数移到结尾,并留有恒定的额外空间

数组包含随机顺序的正数和负数。重新排列数组元素,使所有负数出现在所有正数之前。

例子 :

Input: -12, 11, -13, -5, 6, -7, 5, -3, -6
Output: -12 -13 -5 -7 -3 -6 11 6 5

注意:元素的顺序在这里并不重要。

方法一:
这个想法是简单地应用快速排序的分区过程。

C++
// A C++ program to put all negative
// numbers before positive numbers
#include 
using namespace std;
 
void rearrange(int arr[], int n)
{
    int j = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] < 0) {
            if (i != j)
                swap(arr[i], arr[j]);
            j++;
        }
    }
}
 
// A utility function to print an array
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
}
 
// Driver code
int main()
{
    int arr[] = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    rearrange(arr, n);
    printArray(arr, n);
    return 0;
}


Java
// Java program to put all negative
// numbers before positive numbers
import java.io.*;
 
class GFG {
 
    static void rearrange(int arr[], int n)
    {
        int j = 0, temp;
        for (int i = 0; i < n; i++) {
            if (arr[i] < 0) {
                if (i != j) {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
                j++;
            }
        }
    }
 
    // A utility function to print an array
    static void printArray(int arr[], int n)
    {
        for (int i = 0; i < n; i++)
            System.out.print(arr[i] + " ");
    }
 
    // Driver code
    public static void main(String args[])
    {
        int arr[] = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };
        int n = arr.length;
 
        rearrange(arr, n);
        printArray(arr, n);
    }
}
 
// This code is contributed by Nikita Tiwari.


Python3
# A Python 3 program to put
# all negative numbers before
# positive numbers
 
def rearrange(arr, n ) :
 
    # Please refer partition() in
    # below post
    # https://www.geeksforgeeks.org / quick-sort / j = 0
    j = 0
    for i in range(0, n) :
        if (arr[i] < 0) :
            temp = arr[i]
            arr[i] = arr[j]
            arr[j]= temp
            j = j + 1
    print(arr)
 
# Driver code
arr = [-1, 2, -3, 4, 5, 6, -7, 8, 9]
n = len(arr)
rearrange(arr, n)
 
 
# This code is contributed by Nikita Tiwari.


C#
// C# program to put all negative
// numbers before positive numbers
using System;
 
class GFG {
    static void rearrange(int[] arr, int n)
    {
 
        int j = 0, temp;
        for (int i = 0; i < n; i++) {
            if (arr[i] < 0) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                j++;
            }
        }
    }
 
    // A utility function to print an array
    static void printArray(int[] arr, int n)
    {
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
    }
 
    // Driver code
    public static void Main()
    {
        int[] arr = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };
        int n = arr.Length;
 
        rearrange(arr, n);
        printArray(arr, n);
    }
}
 
// This code is contributed by nitin mittal.


PHP


Javascript


C++
// C++ program of the above
// approach
 
#include 
using namespace std;
 
// Function to shift all the
// negative elements on left side
void shiftall(int arr[], int left,
              int right)
{
   
  // Loop to iterate over the
  // array from left to the right
  while (left<=right)
  {
    // Condition to check if the left
    // and the right elements are
    // negative
    if (arr[left] < 0 && arr[right] < 0)
      left+=1;
     
    // Condition to check if the left
    // pointer element is positive and
    // the right pointer element is negative
    else if (arr[left]>0 && arr[right]<0)
    {
      int temp=arr[left];
      arr[left]=arr[right];
      arr[right]=temp;
      left+=1;
      right-=1;
    }
     
    // Condition to check if both the
    // elements are positive
    else if (arr[left]>0 && arr[right] >0)
      right-=1;
    else{
      left += 1;
      right -= 1;
    }
  }
}
 
// Function to print the array
void display(int arr[], int right){
   
  // Loop to iterate over the element
  // of the given array
  for (int i=0;i<=right;++i){
    cout<


Java
// Java program of the above
// approach
import java.io.*;
 
class GFG{
 
// Function to shift all the
// negative elements on left side
static void shiftall(int[] arr, int left,
                     int right)
{
     
    // Loop to iterate over the
    // array from left to the right
    while (left <= right)
    {
         
        // Condition to check if the left
        // and the right elements are
        // negative
        if (arr[left] < 0 && arr[right] < 0)
            left++;
 
        // Condition to check if the left
        // pointer element is positive and
        // the right pointer element is negative
        else if (arr[left] > 0 && arr[right] < 0)
        {
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
 
        // Condition to check if both the
        // elements are positive
        else if (arr[left] > 0 && arr[right] > 0)
            right--;
        else
        {
            left++;
            right--;
        }
    }
}
 
// Function to print the array
static void display(int[] arr, int right)
{
     
    // Loop to iterate over the element
    // of the given array
    for(int i = 0; i <= right; ++i)
        System.out.print(arr[i] + " ");
         
    System.out.println();
}
 
// Drive code
public static void main(String[] args)
{
    int[] arr = { -12, 11, -13, -5,
                   6, -7, 5, -3, 11 };
                    
    int arr_size = arr.length;
 
    // Function Call
    shiftall(arr, 0, arr_size - 1);
    display(arr, arr_size - 1);
}
}
 
// This code is contributed by dhruvgoyal267


Python3
# Python3 program of the
# above approach
 
# Function to shift all the
# the negative elements to
# the left of the array
def shiftall(arr,left,right):
   
  # Loop to iterate while the
  # left pointer is less than
  # the right pointer
  while left<=right:
     
    # Condition to check if the left
    # and right pointer negative
    if arr[left] < 0 and arr[right] < 0:
      left+=1
       
    # Condition to check if the left
    # pointer element is positive and
    # the right pointer element is
    # negative
    else if arr[left]>0 and arr[right]<0:
      arr[left], arr[right] = \
              arr[right],arr[left]
      left+=1
      right-=1
       
    # Condition to check if the left
    # pointer is positive and right
    # pointer as well
    else if arr[left]>0 and arr[right]>0:
      right-=1
    else:
      left+=1
      right-=1
       
# Function to print the array
def display(arr):
  for i in range(len(arr)):
    print(arr[i], end=" ")
  print()
 
# Driver Code
if __name__ == "__main__":
  arr=[-12, 11, -13, -5, \
       6, -7, 5, -3, 11]
  n=len(arr)
  shiftall(arr,0,n-1)
  display(arr)
 
# Sumit Singh


C#
// C# program of the above
// approach
using System.IO;
using System;
class GFG
{
    // Function to shift all the
    // negative elements on left side
    static void shiftall(int[] arr, int left,int right)
    {
       
        // Loop to iterate over the
        // array from left to the right
        while (left <= right)
        {
          
            // Condition to check if the left
            // and the right elements are
            // negative
            if (arr[left] < 0 && arr[right] < 0)
                left++;
  
            // Condition to check if the left
            // pointer element is positive and
            // the right pointer element is negative
            else if (arr[left] > 0 && arr[right] < 0)
            {
                int temp = arr[left];
                arr[left] = arr[right];
                arr[right] = temp;
                left++;
                right--;
            }
  
            // Condition to check if both the
            // elements are positive
            else if (arr[left] > 0 && arr[right] > 0)
                right--;
            else
            {
                left++;
                right--;
            }
        }
    }
   
    // Function to print the array
    static void display(int[] arr, int right)
    {
       
        // Loop to iterate over the element
        // of the given array
        for(int i = 0; i <= right; ++i)
        {
            Console.Write(arr[i] + " ");
             
        }
        Console.WriteLine();
    }
     
    // Drive code                  
    static void Main()
    {
        int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, 11};
        int arr_size = arr.Length;
        shiftall(arr, 0, arr_size - 1);
        display(arr, arr_size - 1);
    }
}
 
// This code is contributed by avanitrachhadiya2155


Javascript


Java
// Java program to move all negative numbers to the
// beginning and all positive numbers to the end with
// constant extra space
 
public class Gfg {
 
    // a utility function to swap two elements of an array
    public static void swap(int[] ar, int i, int j)
    {
        int t = ar[i];
        ar[i] = ar[j];
        ar[j] = t;
    }
 
    // function to shilf all negative integers to the left
    // and all positive integers to the right
    // using Dutch National Flag Algorithm
    public static void move(int[] ar)
    {
        int low = 0;
        int high = ar.length - 1;
        while (low <= high) {
            if (ar[low] <= 0)
                low++;
            else
                swap(ar, low, high--);
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] ar = { 1, 2,  -4, -5, 2, -7, 3,
                     2, -6, -8, -9, 3, 2,  1 };
        move(ar);
        for (int e : ar)
            System.out.print(e + " ");
    }
}
 
// This code is contributed by Vedant Harshit


C++
#include 
using namespace std;
 
// Swap Function.
void swap(int &a,int &b){
  int temp =a;
  a=b;
  b=temp;
}
   
// Using Dutch National Flag Algorithm.
void reArrange(int arr[],int n){
      int low =0,high = n-1;
      while(low0){
          high--;
      }else{
        swap(arr[low],arr[high]);
      }
    }
}
void displayArray(int arr[],int n){
  for(int i=0;i


输出
-1 -3 -7 4 5 6 2 8 9 

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

双指针方法:这个想法是用恒定空间和线性时间来解决这个问题,方法是使用双指针或双变量方法,我们只需采用两个变量,如左和右,它们分别保存 0 和 N-1 索引。只需要检查:

  1. 检查左右指针元素是否为负,然后简单地增加左指针。
  2. 否则,如果左元素为正而右元素为负,则只需交换元素,同时递增和递减左右指针。
  3. 否则,如果左元素为正且右元素也为正,则只需递减右指针。
  4. 重复以上3个步骤,直到左指针≤右指针。

下面是上述方法的实现:

C++

// C++ program of the above
// approach
 
#include 
using namespace std;
 
// Function to shift all the
// negative elements on left side
void shiftall(int arr[], int left,
              int right)
{
   
  // Loop to iterate over the
  // array from left to the right
  while (left<=right)
  {
    // Condition to check if the left
    // and the right elements are
    // negative
    if (arr[left] < 0 && arr[right] < 0)
      left+=1;
     
    // Condition to check if the left
    // pointer element is positive and
    // the right pointer element is negative
    else if (arr[left]>0 && arr[right]<0)
    {
      int temp=arr[left];
      arr[left]=arr[right];
      arr[right]=temp;
      left+=1;
      right-=1;
    }
     
    // Condition to check if both the
    // elements are positive
    else if (arr[left]>0 && arr[right] >0)
      right-=1;
    else{
      left += 1;
      right -= 1;
    }
  }
}
 
// Function to print the array
void display(int arr[], int right){
   
  // Loop to iterate over the element
  // of the given array
  for (int i=0;i<=right;++i){
    cout<

Java

// Java program of the above
// approach
import java.io.*;
 
class GFG{
 
// Function to shift all the
// negative elements on left side
static void shiftall(int[] arr, int left,
                     int right)
{
     
    // Loop to iterate over the
    // array from left to the right
    while (left <= right)
    {
         
        // Condition to check if the left
        // and the right elements are
        // negative
        if (arr[left] < 0 && arr[right] < 0)
            left++;
 
        // Condition to check if the left
        // pointer element is positive and
        // the right pointer element is negative
        else if (arr[left] > 0 && arr[right] < 0)
        {
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
 
        // Condition to check if both the
        // elements are positive
        else if (arr[left] > 0 && arr[right] > 0)
            right--;
        else
        {
            left++;
            right--;
        }
    }
}
 
// Function to print the array
static void display(int[] arr, int right)
{
     
    // Loop to iterate over the element
    // of the given array
    for(int i = 0; i <= right; ++i)
        System.out.print(arr[i] + " ");
         
    System.out.println();
}
 
// Drive code
public static void main(String[] args)
{
    int[] arr = { -12, 11, -13, -5,
                   6, -7, 5, -3, 11 };
                    
    int arr_size = arr.length;
 
    // Function Call
    shiftall(arr, 0, arr_size - 1);
    display(arr, arr_size - 1);
}
}
 
// This code is contributed by dhruvgoyal267

Python3

# Python3 program of the
# above approach
 
# Function to shift all the
# the negative elements to
# the left of the array
def shiftall(arr,left,right):
   
  # Loop to iterate while the
  # left pointer is less than
  # the right pointer
  while left<=right:
     
    # Condition to check if the left
    # and right pointer negative
    if arr[left] < 0 and arr[right] < 0:
      left+=1
       
    # Condition to check if the left
    # pointer element is positive and
    # the right pointer element is
    # negative
    else if arr[left]>0 and arr[right]<0:
      arr[left], arr[right] = \
              arr[right],arr[left]
      left+=1
      right-=1
       
    # Condition to check if the left
    # pointer is positive and right
    # pointer as well
    else if arr[left]>0 and arr[right]>0:
      right-=1
    else:
      left+=1
      right-=1
       
# Function to print the array
def display(arr):
  for i in range(len(arr)):
    print(arr[i], end=" ")
  print()
 
# Driver Code
if __name__ == "__main__":
  arr=[-12, 11, -13, -5, \
       6, -7, 5, -3, 11]
  n=len(arr)
  shiftall(arr,0,n-1)
  display(arr)
 
# Sumit Singh

C#

// C# program of the above
// approach
using System.IO;
using System;
class GFG
{
    // Function to shift all the
    // negative elements on left side
    static void shiftall(int[] arr, int left,int right)
    {
       
        // Loop to iterate over the
        // array from left to the right
        while (left <= right)
        {
          
            // Condition to check if the left
            // and the right elements are
            // negative
            if (arr[left] < 0 && arr[right] < 0)
                left++;
  
            // Condition to check if the left
            // pointer element is positive and
            // the right pointer element is negative
            else if (arr[left] > 0 && arr[right] < 0)
            {
                int temp = arr[left];
                arr[left] = arr[right];
                arr[right] = temp;
                left++;
                right--;
            }
  
            // Condition to check if both the
            // elements are positive
            else if (arr[left] > 0 && arr[right] > 0)
                right--;
            else
            {
                left++;
                right--;
            }
        }
    }
   
    // Function to print the array
    static void display(int[] arr, int right)
    {
       
        // Loop to iterate over the element
        // of the given array
        for(int i = 0; i <= right; ++i)
        {
            Console.Write(arr[i] + " ");
             
        }
        Console.WriteLine();
    }
     
    // Drive code                  
    static void Main()
    {
        int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, 11};
        int arr_size = arr.Length;
        shiftall(arr, 0, arr_size - 1);
        display(arr, arr_size - 1);
    }
}
 
// This code is contributed by avanitrachhadiya2155

Javascript


输出
-12 -3 -13 -5 -7 6 5 11 11 

这是一种就地重新排列算法,用于在不保持元素顺序的情况下排列正数和负数。

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

如果我们需要保持元素的顺序,问题就会变得困难。有关详细信息,请参阅使用恒定额外空间重新排列正负数。

方法3:

在这里,我们将使用著名的荷兰国旗算法来处理两种“颜色”。第一种颜色适用于所有负整数,第二种颜色适用于所有正整数。我们将借助两个指针低和高将数组分成三个分区。

1. ar[1…low-1] 负整数

2. ar[低…高] 未知

3. ar[high+1…N] 正整数

现在,我们在低指针的帮助下探索数组,缩小未知分区,并在此过程中将元素移动到正确的分区。我们这样做直到我们探索了所有元素,并且未知分区的大小缩小到零。

下面是上述方法的实现:

Java

// Java program to move all negative numbers to the
// beginning and all positive numbers to the end with
// constant extra space
 
public class Gfg {
 
    // a utility function to swap two elements of an array
    public static void swap(int[] ar, int i, int j)
    {
        int t = ar[i];
        ar[i] = ar[j];
        ar[j] = t;
    }
 
    // function to shilf all negative integers to the left
    // and all positive integers to the right
    // using Dutch National Flag Algorithm
    public static void move(int[] ar)
    {
        int low = 0;
        int high = ar.length - 1;
        while (low <= high) {
            if (ar[low] <= 0)
                low++;
            else
                swap(ar, low, high--);
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int[] ar = { 1, 2,  -4, -5, 2, -7, 3,
                     2, -6, -8, -9, 3, 2,  1 };
        move(ar);
        for (int e : ar)
            System.out.print(e + " ");
    }
}
 
// This code is contributed by Vedant Harshit

C++

#include 
using namespace std;
 
// Swap Function.
void swap(int &a,int &b){
  int temp =a;
  a=b;
  b=temp;
}
   
// Using Dutch National Flag Algorithm.
void reArrange(int arr[],int n){
      int low =0,high = n-1;
      while(low0){
          high--;
      }else{
        swap(arr[low],arr[high]);
      }
    }
}
void displayArray(int arr[],int n){
  for(int i=0;i
输出
-9 -8 -4 -5 -6 -7 2 3 2 2 3 2 1 1 

时间复杂度: O(N)

辅助空间: O(1)

元素的顺序在这里无关紧要。 Vedant Harshit提供的解释和代码