1.首先要知道转置的话是前面的元素与后面的元素进行交换
2.寻找规律,等到 x=temp[].length-1-x;
3.最后是判断这个置换的次数,如果每次都置换了,发现并没改变,那是因为又换回去了,所以循环的次数只有数组长度的一般。
public class 数组转置 { public static void main(String[] args) { int[] data=new int[] {1,2,3,4,5,6,7,8}; print(data); transfer(data); print(data); } public static int[] transfer(int[] temp) { for(int x=0;x<temp.length/2;x++) { int tem=temp[x]; temp[x]=temp[temp.length-1-x]; temp[temp.length-1-x]=tem; } return temp; } public static void print(int[] temp) { for(int x=0;x<temp.length;x++) { System.out.print(temp[x]); } System.out.println(); } }
第二种方法是引用了指针的概念
把索引当作指向数据的工具
int tem=temp[head]; temp[head]=temp[end]; temp[end]=tem; head++; end--;
下面是完整代码
public class 数组转置 { public static void main(String[] args) { int[] data=new int[] {1,2,3,4,5,6,7,8}; print(data); transfer(data); print(data); } public static int[] transfer(int[] temp) { int head=0; int end=temp.length-1; int center=temp.length/2; for(int x=0;x<center;x++) { int tem=temp[head]; temp[head]=temp[end]; temp[end]=tem; head++; end--; } return temp; } public static void print(int[] temp) { for(int x=0;x<temp.length;x++) { System.out.print(temp[x]); } System.out.println(); } }