• 一维数组转置


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

      

  • 相关阅读:
    mysql 查询某年某月数据~(如果数据表用时间戳)
    mongo_4.25 find() hasNext() next()
    在YII框架中有2中方法创建对象:
    bootsrap[$data]
    date
    cookie
    JavaScript shell, 可以用到 JS 的特性, forEach
    在 Yii框架中使用session 的笔记:
    mysql查询今天、昨天、7天、近30天、本月、上一月 数据
    Python 自定义异常练习
  • 原文地址:https://www.cnblogs.com/cainame/p/10318974.html
Copyright © 2020-2023  润新知