日期:2014-05-20 浏览次数:20925 次
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] } }
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.
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] } }
------解决方案--------------------
智慧有限,没想出什么新意来,出去玩了一天,活跃下脑子.
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); }
------解决方案--------------------
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] } }