【问题标题】:Reversing a Generic Array using "in situ"使用“原位”反转通用数组
【发布时间】:2015-06-03 18:08:39
【问题描述】:

对于这个通用数组,我添加了方法 reverse(),它必须在不使用其他元素数组的情况下反转数组,并且我尝试仅使用交换操作“原位”执行反转。但我可能弄错了,如果是这样,如何仅使用交换操作“原地”反转它?

import java.util.Collections;

class GenericArray<E> {
    private E[] array;
    private int size;

    public GenericArray() {
        array = (E[]) new Object[10];
        size = 0;
    }

    public E get(int i) {
        return array[i];
    }

    public void set(int i, E value) {
        if (i < size)
            array[i] = value;
    }

    public void add(E value) {
        array[size++] = value;
    }

    public boolean isFull() {
        return size == array.length;
    }

    public void remove(int i) {
        for (int j = i; j < size; j++)
            array[j] = array[j + 1];
        size--;
    }

    public void insert(int i, E value) {
        for (int j = size; j >= i; j--)
            array[j + 1] = array[j];
        array[i] = value;
        size++;
    }

    public void display() {
        for (int i = 0; i < size; i++)
            System.out.print(array[i] + " ");
        System.out.println();
    }

    public E reverse() {

        Collections.reverse(array);

    }

}

【问题讨论】:

标签: java arrays algorithm generics reverse


【解决方案1】:

如果您的意思是不使用Collections.reverse 手动执行此操作(顺便说一句,该代码甚至不应该编译,reverse 需要List 作为参数),只需从开头遍历数组到中间交换元素在范围的相对两侧:

public E[] reverse() {
    for (int i = 0; i < size/2; i++){
        E tmp=array[i];  
        array[i] = array[size - i - 1];
        array[size - i - 1]=tmp;
    }
    return array; // If you really want to return it
}

更多关于维基百科in situ algorithms的信息。

关于确保有足够空间的add 实现:

public void add(E value) {
    int newsize=size+1;
    if(newsize<size){
        //The array is big enough, add the element
        array[newsize]=value;
    }else{
        //The array is too small, create a new one with
        //the old content but twice as bigger and add 
        //the new element
        array=Arrays.copyOf(array,size*2); 
        array[newsize]=value;  
    }
    size=newsize;
}

【讨论】:

  • 所以我猜这将被视为“原位”而不使用额外的元素数组并且仅使用交换操作。
  • 是的,“in situ”是拉丁语中“in place”的意思,3 行正在执行交换。
  • 哦!我认为“原位”在编程和 Java 中意味着一些特殊的东西。
  • 实际上确实如此,在维基百科上他们甚至使用与示例相同的算法:en.wikipedia.org/wiki/In-place_algorithm
  • 还有@uraimo 我如何更正 add() 方法以增加存储数组的大小,因为不再可能在数组已满时添加元素。另外我怎么能更正插入方法()以增加存储数组的大小,因为在数组已满时插入元素不再可能?
【解决方案2】:

Collections.reverse()“原位”反转;您只需要将数组作为列表提供:

Collections.reverse(Arrays.asList(array));

【讨论】:

  • 谢谢!现在,如果您查看 uraimo 和我在谈论的内容,我正在尝试“更正 add() 方法以增加存储数组的大小,因为不再可能在数组已满时添加元素。也正确插入方法()来增加存储数组的大小,因为不再可能在数组已满时插入元素“
猜你喜欢
  • 2018-07-06
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 1970-01-01
  • 1970-01-01
  • 2021-04-23
  • 2015-09-17
  • 2016-02-27
相关资源
最近更新 更多