如何返回java中元素的当前索引?

[i, j]具有属性i < j和A[i] ≥ A[j](即反转)的一对位置,这样A[i] − A[j]是 A 中所有反转中可能的最大值。


    class Main {

    static int[] diff(int arr[], int n){

     int index1=0;

     int index2=0;

     int maxdiff=0;

     int[] ans=new int[3];

     int i,j;

     for (i=0; i<n; ++i){

       for (j=n-1; j>i; --j){

         if(arr[i]>arr[j] && maxdiff<arr[i]-arr[j])

         maxdiff=arr[i]-arr[j];

         index1=i;

         index2=j;

         ans[0]=index1;

         ans[1]=index2; 

         ans[2]=maxdiff;


      }

     }

    return ans;


    }


     public static void main(String[] args) {

       Main max = new Main();

       int arr[]={1,20,2,6,11,16,8};

       int n=arr.length;

       int[] ans=max.diff(arr, n);

        System.out.println("i="+ans[0]);

        System.out.println("j=" + ans[1]);

        System.out.println(ans[2]);

      }

    }

正如你所看到的,我想打印i=2,j=3因为arr[2]-arr[3]这是最大的反转,如果有人能给我一些建议,我将不胜感激。


慕标琳琳
浏览 70回答 1
1回答

噜噜哒

public class Main {static int[] diff(int arr[], int n){&nbsp;int index1=0;&nbsp;int index2=0;&nbsp;int maxdiff=0;&nbsp;int[] ans=new int[3];&nbsp;int i,j;&nbsp;for (i=0; i<n-1; ++i){//&nbsp; &nbsp;for (j=i+1; j>i; --j){//&nbsp; &nbsp; &nbsp;if(arr[i]>arr[j] && maxdiff<Math.abs(arr[i]-arr[j]))//&nbsp; &nbsp; &nbsp;maxdiff=Math.abs(arr[i]-arr[j]);//&nbsp; &nbsp; &nbsp;index1=i;//&nbsp; &nbsp; &nbsp;index2=j;//&nbsp; &nbsp; &nbsp;ans[0]=index1;//&nbsp; &nbsp; &nbsp;ans[1]=index2;&nbsp;//&nbsp; &nbsp; &nbsp;ans[2]=maxdiff;////&nbsp; }&nbsp; &nbsp; &nbsp;if(maxdiff<Math.abs(arr[i]-arr[i+1]))&nbsp; &nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;maxdiff=Math.abs(arr[i]-arr[i+1]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ans[0]=i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ans[1]=i+1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ans[2]=maxdiff;&nbsp; &nbsp; &nbsp;}&nbsp;}return ans;}&nbsp;public static void main(String[] args) {&nbsp; &nbsp;Main max = new Main();&nbsp; &nbsp;int arr[]={1,20,2,6,11,16,8};&nbsp; &nbsp;int n=arr.length;&nbsp; &nbsp;int[] ans=max.diff(arr, n);&nbsp; &nbsp; System.out.println("i="+ans[0]);&nbsp; &nbsp; System.out.println("j=" + ans[1]);&nbsp; &nbsp; System.out.println(ans[2]);&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java