在O(n)时间和O(1)空间中将所有x元素推送到数组的末尾

时间:2014-12-15 10:21:51

标签: java arrays algorithm

我正在尝试解决算法任务,但遗憾的是无法为它提出一些最佳方法。我们得到一个数组,任务是将所有元素x移动到数组的末尾。对于例如
输入[1,2,3,4,1,2,3,4,5,6,5]
输出[2, 3, 4, 2, 3, 4, 5, 6, 5, 1, 1]

3 个答案:

答案 0 :(得分:1)

你可以像这样实现它

import java.util.Arrays;

public class Rearrange
{

    public static void main(String args[]) {
       int arr[] = {1,2,3,4,1,2,3,4,5,6,5};
        reArrange(arr, 1);
        System.out.println(Arrays.toString(arr));
    }

    private static void reArrange(int[] arr, int x) {
        int index = 0;
        for (int current : arr)
            if (current != x)
                arr[index++] = current;
        Arrays.fill(arr, index, arr.length, x);
    }

}

输出

[2, 3, 4, 2, 3, 4, 5, 6, 5, 1, 1]

答案 1 :(得分:0)

以下是我提出的C++算法实现。我不确定正确性,但我测试了不同的x并且它有效。你可以从中找出算法:

#include<iostream>
#include<cstdio>
using namespace std;
void swap (int a[], int i, int j) {
    int temp;
    temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}
void move_to_end(int a[], int x, int size) {
    bool flag = 0;
    int s_i;
    for (int i = 0; i < size; i++) {
        if(flag) {
            if(a[i] != x) {
                swap(a, s_i, i);
                s_i++;
            }
        }
        else {
            if(a[i] == x) {
                flag = 1;
                s_i = i;
            }
        }
    }
}
int main () {
    int a[] = {1,2,3,4,1,2,3,4,5,6,1,6,5,1,2,3};
    int size = 16;
    int x = 1;
    move_to_end(a, x, size);
    for (int i = 0; i < size; i++) {
        cout << a[i] << " ";
    }
    cout << endl;
}

<强>输出:

2 3 4 2 3 4 5 6 6 5 2 3 1 1 1 1

答案 2 :(得分:0)

To= 0;
for (From= 0; From < Length; From++)
  if (A[From] != 1)
  {
    A[To]= A[From];
    To++;
  }

for ( ; To < Length; To++)
  A[To]= 1;