zoukankan      html  css  js  c++  java
  • 一维数组转置

    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();
    		}
    }
    

      

  • 相关阅读:
    ubuntu安装后要做什么
    JavaScript错误处理
    jQuery 事件
    display的用法
    百度排名的原理
    什么是ajax?
    CSS文档流
    引用CSS的方法
    jQuery的安装方式
    禁止WPS2019开机自启动
  • 原文地址:https://www.cnblogs.com/cainame/p/10318974.html
Copyright © 2011-2022 走看看