0

私は、最大の 3 つの数値を含む配列を作成しようとする方法に取り組んでいました。しかし、コードにエラーがあり、何が間違っていたのか理解できませんでした。ありがとう!

パブリック クラス Method3 {

public static void main(String[] args) {
    int[] a={2,5,6,7,9,1,2,3,5,9,7};

    System.out.print(largestSum(a));


}


public static int[] largestSum(int[] a){

    int temp, first, second, third;
    first=second=third=a[0];

    for(int element: a){

        if(first < element)
            {
                temp=first;
                first=element;
                second=temp;
            }

        if(second<element && first> element)
            {

                temp=element;
                second=element;
                third=temp;
            }

        if(third< element && second> element)
            {
            temp=element;
            third=element;

            }

    }

    int [] array=new int[3];
    array[0]=first;
    array[1]=second;
    array[3]=third;



    return array;
}

}

4

2 に答える 2

2

いくつかのケースを見逃しました:この値は 1 回しか有効ではないためfirst、 ,secondthirdすべて初期化することはできません。a[0]

first=second=third=Integer.MIN_VALUE;

for(int element: a){
    if(first <= element){
            third=second;
            second=first;
            first=element;
            continue;
    }
    if(second <= element ){
            third=second;
            second=element;
            continue;
    }
    if(third < element){
            third=element;
    }
}
于 2013-01-26T19:57:33.257 に答える
0

あなたが持っているものにはいくつかの問題があります。すべての値を設定すると、 が最大のa[0]場合a[0]は更新されません。最初の最大値を更新すると、3 番目ではなく 2 番目の値が失われます。また、3 要素配列では無効な array[3] を設定しています。

試す。

  public static int[] largestSum(int[] a)
  {
    int largest[3] = {Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE};

    for(int i = 0; i < a.length; i++)
    {
       if(a[i] > largest[0])
       {
          largest[2] = largest[1];
          largest[1] = largest[0];
          largest[0] = a[i];
       }
       else if(a[i] > largest[1])
       {
          largest[2] = largest[1];
          largest[1] = a[i];
       }
       else if(a[i] > largest[2])
       {
         largest[2] = a[i];
       }
    }

    return largest;
 }
于 2013-01-26T19:58:47.263 に答える