日期:2014-05-20  浏览次数:20925 次

【小测试】用递归的方法,颠倒整型数组的数据顺序
Java code
class T {

  public static void reverse(int[] a, int left, int right) {
    // 代码写在这里

  }

  public static void main(String args[]) throws Exception {
    int[] a = { 1, 2, 3, 4, 5 };
    reverse(a, 0, a.length - 1);
    System.out.println(Arrays.toString(a)); // 得到 [5, 4, 3, 2, 1] 
  }
}


------解决方案--------------------
import java.util.Arrays;

class T {
private static StringBuilder builder = new StringBuilder();
public static void reserse(int[] a, int left, int right) {
int t = 0;
t = a[right];
a[right] = a[left];
a[left] = t;
if(a.length / 2 == left + 1 || a.length / 2 == right - 1){
return;
}
reserse(a, left + 1, right - 1);

}

public static void main(String args[]) throws Exception {
int[] a = { 1, 2, 3, 4, 5 };
reserse(a, 0, a.length - 1);
System.out.println(Arrays.toString(a)); // 得到 [5, 4, 3, 2, 1] 
}
}
------解决方案--------------------
先大体写一个再考虑别的
Java code

public static void reverse(int[] a, int left, int right) {
        // 代码写在这里
        if (left == right) {  //数组长度为奇数
            return;
        }
        if (left + 1 == right) {  //数组长度为偶数
            int temp = a[left];
            a[left] = a[right];
            a[right] = temp;
        } else {
            int temp = a[left];
            a[left] = a[right];
            a[right] = temp;
            reverse(a, left + 1, right - 1);
        }
    }

------解决方案--------------------
Please allow me to give a simple input. Thanks.

Java code

class T {

  public static void reverse(int[] a, int left, int right) {
    if (left < right) {
      int tmp = a[left];
      a[left] = a[right];
      a[right] = tmp;
      reverse(a, ++left, --right);
    }
  }

  public static void main(String args[]) throws Exception {
    int[] a = { 1, 2, 3, 4, 5 };
    reverse(a, 0, a.length - 1);
    System.out.println(Arrays.toString(a)); // 得到 [5, 4, 3, 2, 1] 
  }
}

------解决方案--------------------
智慧有限,没想出什么新意来,出去玩了一天,活跃下脑子.
Java code

    public static void reverse(int[] a, int left, int right) {
        if (left >= right)
            return;
        int temp=a[left];
        a[left]=a[right];
        a[right]=temp;
        reverse(a,++left,--right);
    }

------解决方案--------------------
Java code
import java.util.Arrays;

/**
 * 该类创建于 2008-10-1 下午08:41:40
 * 
 * @version 1.0.0
 * @author 侯磊
 */
public class T {
    public static void reverse(int[] a, int left, int right) {
        // 代码写在这里
        if(left>=right)return;
        reverse(a,left+1,right-1);
        a[left]=a[left]+a[right];
        a[right]=a[left]-a[right];
        a[left]=a[left]-a[right];
    }

    public static void main(String args[]) throws Exception {
        int[] a = { 1, 2, 3, 4, 5 };
        reverse(a, 0, a.length - 1);
        System.out.println(Arrays.toString(a)); // 得到 [5, 4, 3, 2, 1]
    }

}