Java,我是新手,帮忙下,先谢了!将一个已知数组中所有元素的次序颠倒为相反次序,怎么用Java语言编写呀
将已知数组[1234567]中所有元素颠倒为相反次序[7654321],并分析时间复杂度和空间复杂度,谢谢啦,给个答案,还有要分析复杂度,好像程序看头是publiccla...
将已知数组[1 2 3 4 5 6 7]中所有元素颠倒为相反次序[7654321],并分析时间复杂度和空间复杂度,谢谢啦,给个答案,还有要分析复杂度,好像程序看头是public class ArrayRev
{
public static void reverseArray(int x[]),往后不会了 展开
{
public static void reverseArray(int x[]),往后不会了 展开
1个回答
2013-07-04
展开全部
package com.tarena.day10;import java.util.Arrays;public class Test1 { public static void main(String[] args){
int[] ary = {1,2,3,4,5,6,7};
System.out.println(Arrays.toString(reverseArray(ary)));
System.out.println(Arrays.toString(reverseArray1(ary)));
}
// 方法一:(时间复杂度: T(n) = T(7); 空间复杂度: O(n) = O(7))
public static int[] reverseArray(int[] ary){
int[] x = new int[7];
int j = 0;
for(int i = ary.length - 1; i > -1; i --){
x[j++] = ary[i];
}
return x;
}
// 方法二:(时间复杂度: T(n) = T(3); 空间复杂度: O(n) = O(1))
public static int[] reverseArray1(int[] ary){
int temp;
for(int i = ary.length - 1; i > 3; i--){
temp = ary[i];
ary[i] = ary[ary.length - 1 - i];
ary[ary.length - 1 - i] = temp;
}
return ary;
}
}
int[] ary = {1,2,3,4,5,6,7};
System.out.println(Arrays.toString(reverseArray(ary)));
System.out.println(Arrays.toString(reverseArray1(ary)));
}
// 方法一:(时间复杂度: T(n) = T(7); 空间复杂度: O(n) = O(7))
public static int[] reverseArray(int[] ary){
int[] x = new int[7];
int j = 0;
for(int i = ary.length - 1; i > -1; i --){
x[j++] = ary[i];
}
return x;
}
// 方法二:(时间复杂度: T(n) = T(3); 空间复杂度: O(n) = O(1))
public static int[] reverseArray1(int[] ary){
int temp;
for(int i = ary.length - 1; i > 3; i--){
temp = ary[i];
ary[i] = ary[ary.length - 1 - i];
ary[ary.length - 1 - i] = temp;
}
return ary;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询