2012-12-01 3 views
0

나는 1, 2 및 3 번째로 큰 배열을 찾아야합니다. 나는 그것을 단순히 정렬하고 배열 [0], 배열 [1], 배열 [3]을 반환 할 수 있음을 안다. 그러나 문제는 가치가 아니라 지수가 필요하다는 것입니다. 내가 float[] listx={8.0, 3.0, 4.0, 5.0, 9.0}이있는 경우 예를 들어는 0, 4 반환해야하고, 여기에두 번째 및 세 번째 최대 요소 배열 자바를 찾으십시오

3. 내가 가지고있는 코드입니다하지만 작동하지 않습니다

//declaration max1-3   
public void maxar (float[] listx){ 

    float maxel1=0; 
    float maxel2=0; 
    float maxel3=0; 

    for (int i=0; i<listx.length; i++){ 
     if(maxel1<listx[i]) 
     {maxel1=listx[i]; 
     max1=i; 
     } 
    } 
    listx[max1]=0; //to exclude this one in nextsearch 

    for (int j=0; j<listx.length; j++){ 
     if(listx[j]>maxel2) 
     {maxel2=listx[j]; 
     max2=j; 
     } 
    } 
    listx[max2]=0; 

    for (int k=0; k<listx.length; k++){ 
     if(listx[k]>maxel3) 
     {maxel3=listx[k]; 
     max3=k; 
     } 
    } 
} 

을 내가 max1 권리를 얻을 수 있지만 모든 요소 후 따라서 max2와 max3은 0이됩니다.이 솔루션에 무엇이 잘못 되었습니까? 고맙습니다.

+0

확인 [이] (http://stackoverflow.com/questions/2615712/finding-the-second- 가장 높은 숫자의 배열) 게시물 –

답변

0

배열을 통해 3 개 패스합니다 인 제 1 패스 찾기 값 및 제 2 패스 찾기 값 및 최대 요소 M2의 첫번째 인덱스의 최대 요소 M1의 첫번째 인덱스에 덜보다 M1 및 세 번째 패스 찾기 값/1 인덱스 M3 < M2에 .

+2

3 패스는 잔인합니다. 한 번만 통과하면됩니다. –

2

단일 루프를 사용하여 세 요소를 찾을 수 있으며 배열을 수정할 필요가 없습니다.

새로운 가장 큰 요소를 발견하면 가장 큰 이전 요소와 이전의 두 번째 요소를 한 위치 아래로 이동해야합니다.

마찬가지로 두 번째로 큰 새로운 요소를 발견하면 maxel2maxel3으로 변경해야합니다.

세 변수를 사용하는 대신 배열을 사용할 수 있습니다. 이렇게하면 논리를 간소화하고 최대 요소 인 k으로 쉽게 일반화 할 수 있습니다.

0

것은 내가 하나의 패스를 만드는 대신 최적화를위한 세 가지 제안이 작동이 코드 :

public class Array 
    { 
    public void getMax(double ar[]) 
    { 
    double max1 = ar[0]; // Assume the first 
    double max2 = ar[0]; // element in the array 
    double max3 = ar[0]; // is the maximum element. 
    int ZERO = 0; 
    // Variable to store inside it the index of the max value to set it to zero. 

    for(int i = 0; i < ar.length; i++) 
    { 
     if(ar[i] >= max1) 
     { 
      max1 = ar[i]; 
      ZERO = i; 
     } 
    } 

    ar[ZERO] = 0; // Set the index contains the 1st max to ZERO. 

    for(int j = 0; j < ar.length; j++) 
    { 
     if(ar[j] >= max2) 
     { 
      max2 = ar[j]; 
      ZERO = j; 
     } 
    } 

    ar[ZERO] = 0; // Set the index contains the 2st max to ZERO. 

    for(int k = 0; k < ar.length; k++) 
    { 
     if(ar[k] >= max3) 
     { 
      max3 = ar[k]; 
      ZERO = k; 
     } 
    } 

      System.out.println("1st max:" + max1 + ", 2nd: " +max2 + ",3rd: "+ max3);        
    } 

public static void main(String[] args) 
{ 
    // Creating an object from the class Array to be able to use its methods. 
    Array array = new Array(); 
    // Creating an array of type double. 
    double a[] = {2.2, 3.4, 5.5, 5.5, 6.6, 5.6}; 

    array.getMax(a); // Calling the method that'll find the 1st max, 2nd max, and  and 3rd max. 
} 

    } 
0

을보십시오. 아래 코드는 나를 위해 작동합니다. 이 코드에서는 listx에 적어도 세 개의 요소가 있다고 주장하지 않습니다. 2 개 이하의 요소 만 포함될 경우 어떤 일이 발생할지 결정하는 것은 당신에게 달려 있습니다.

내가이 코드에 대해 좋아하는 점은 배열을 한 번 통과하는 것인데, 이는 최상의 경우에는 listx의 요소 수에 비례하는 요소로 3 회의 패스를 수행하는 것보다 빠른 실행 시간을 갖는 것입니다.

는 I1, I2I3 저장소 listx의 삼대 요소의 인덱스 및 I0I1, I2 가장 작은 요소를 가리키는 I3 중 하나를 가정한다. 처음에는 i1 = i2 = i3이므로 아직 가장 큰 요소를 찾지 못했습니다. 그래서 i0 = i1이라고합시다. 새 인덱스 jlistx[j] > listx[i0] 인 것을 발견하면 i0 = j으로 설정하고 이전 색인을 더 큰 요소로 연결하는 색인으로 바꿉니다. 그런 다음 i1, i2i3 중에서 색인이 3 개 중 가장 작은 요소로 이어 지므로 은 새로운 큰 요소가있는 경우에 대비하여으로 안전하게 삭제할 수 있습니다.

참고 :이 코드는 C로되어 있으므로 사용하려면 Java로 변환하십시오. 나는 그것을 쉽게하기 위해 비슷한 구문을 사용했다. (I 자바 테스트 환경이 부족하기 때문에 나는 C에 썼다.)

void maxar(float listx[], int count) { 
    int maxidx[3] = {0}; 

    /* The index of the 3rd greatest element 
    * in listx. 
    */ 
    int max_3rd = 0; 

    for (int i = 0; i < count; i++) { 
     if (listx[maxidx[max_3rd]] < listx[i]) { 
      /* Exchange 3rd greatest element 
      * with new greater element. 
      */ 
      maxidx[max_3rd] = i; 

      /* Find index of smallest maximum. */ 
      for (int j = (max_3rd + 1) % 3; j != max_3rd; j = (j + 1) % 3) { 
       if (listx[maxidx[j]] < listx[maxidx[max_3rd]]) { 
        max_3rd = j; 
       } 
      } 
     } 
    } 

    /* `maxidx' now contains the indices of 
    * the 3 greatest values in `listx'. 
    */ 

    printf("3 maximum elements (unordered):\n"); 
    for (int i = 0; i < 3; i++) { 
     printf("index: %2d, element: %f\n", maxidx[i], listx[maxidx[i]]); 
    } 
} 
0
public class ArrayExample { 
    public static void main(String[] args) { 
     int secondlargest = 0; 
     int thirdLargest=0; 
     int largest = 0; 
     int arr[] = {5,4,3,8,12,95,14,376,37,2,73}; 
     for (int i = 0; i < arr.length; i++) { 
      if (largest < arr[i]) { 
       secondlargest = largest; 
       largest = arr[i]; 
      } 
      if (secondlargest < arr[i] && largest != arr[i]) 
       secondlargest = arr[i]; 
      if(thirdLargest<arr[i] && secondlargest!=arr[i] && largest!=arr[i] && thirdLargest<largest && thirdLargest<secondlargest) 
       thirdLargest =arr[i]; 
     } 
     System.out.println("Largest number is: " + largest); 
     System.out.println("Second Largest number is: " + secondlargest); 
     System.out.println("third Largest number is: " + thirdLargest); 
    } 
} 
0
def third_mar_array(arr): 
    max1=0 
    max2=0 
    max3=0 
    for i in range(0,len(arr)-1): 
     if max1<arr[i]: 
      max1=arr[i] 
      max_in1=i 
    arr[max_in1]=0 
    for j in range(0,len(arr)-1): 
     if max2<arr[j]: 
      max2=arr[j] 
      max_in2=j 
    arr[max_in2]=0 
    for k in range(0,len(arr)-1): 
     if max3<arr[k]: 
      max3=arr[k] 
      max_in3=k 
    #arr[max_in3]=0 
    return max3 

n=[5,6,7,3,2,1] 

f=first_array(n) 
print f 
+0

제안하는 솔루션에 대한 설명을 추가하십시오. –

관련 문제