首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

【小测试】用递归的步骤,颠倒整型数组的数据顺序

2011-12-11 
【小测试】用递归的方法,颠倒整型数组的数据顺序Java codeclass T {public static void reverse(int[] a, in

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

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]    }} 

热点排行