Нахождение второго по величине числа в массиве - PullRequest
26 голосов
/ 11 апреля 2010

Мне сложно понять логику метода, чтобы найти второе по величине число в массиве. Используемый метод состоит в том, чтобы найти самое высокое в массиве, но меньше, чем предыдущее самое высокое (которое уже было найдено). То, что я до сих пор не могу понять, это то, почему || highest_score == second_highest необходимо. Например, я ввожу три числа: 98, 56, 3. Без него как наивысшее, так и второе наивысшее будет 98. Пожалуйста, объясните.

int second highest = score[0];  
if (score[i] > second_highest && score[i] < highest_score || highest_score == second_highest)   
    second_highest = score[i];

Ответы [ 39 ]

0 голосов
/ 02 марта 2016

Пожалуйста, попробуйте это: используя этот метод, вы можете оштрафовать второе по величине число в массиве, даже если массив содержит случайное число. Первый цикл используется для решения проблемы, если наибольшее число идет первым индексом массива.

public class secondLargestnum {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] array = new int[6];
        array[0] = 10;
        array[1] = 80;
        array[2] = 5;
        array[3] = 6;
        array[4] = 50;
        array[5] = 60;
        int tem = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[0]>array[i]) {
                tem = array[0];
            array[0] = array[array.length-1];
            array[array.length-1] = tem;
            }
        }
        Integer largest = array[0];
        Integer second_largest = array[0];

        for (int i = 0; i < array.length; i++) {

            if (largest<array[i]) {
                second_large = largest;
                largest = array[i];
            }
            else if (second_large<array[i]) {
                second_large = array[i];

            }

        }
System.out.println("largest number "+largest+" and second largest number "+second_largest);

    }

}
0 голосов
/ 04 февраля 2016

Второй по величине в O (n / 2)

public class SecMaxNum {

    // second Largest number with O(n/2)
    /**
     * @author Rohan Kamat
     * @Date Feb 04, 2016
     */
    public static void main(String[] args) {
        int[] input = { 1, 5, 10, 11, 11, 4, 2, 8, 1, 8, 9, 8 };
        int large = 0, second = 0;

        for (int i = 0; i < input.length - 1; i = i + 2) {
            // System.out.println(i);
            int fist = input[i];
            int sec = input[i + 1];
            if (sec >= fist) {
                int temp = fist;
                fist = sec;
                sec = temp;
            }
            if (fist >= second) {
                if (fist >= large) {
                    large = fist;
                } else {
                    second = fist;
                }

            }

            if (sec >= second) {
                if (sec >= large) {
                    large = sec;
                } else {
                    second = sec;
                }
            }
        }
    }
}
0 голосов
/ 18 ноября 2015
public class SecondandThirdHighestElement {
    public static void main(String[] args) {
        int[] arr = {1,1,2,3,8,1,2,3,3,3,2,3,101,6,6,7,8,8,1001,99,1,0};
        // create three temp variable and store arr of first element in that temp variable so that it will compare with other element
        int firsttemp = arr[0];
        int secondtemp = arr[0];
        int thirdtemp = arr[0];
        //check and find first highest value from array by comparing with other elements if found than save in the first temp variable 
        for (int i = 0; i < arr.length; i++) {
            if(firsttemp <arr[i]){
                firsttemp =  arr[i];
            }//if

        }//for
        //check and find the second highest variable by comparing with other elements in an array and find the element and that element should be smaller than first element array
        for (int i = 0; i < arr.length; i++) {
            if(secondtemp < arr[i] && firsttemp>arr[i]){
                secondtemp = arr[i];
            }//if
        }//for
        //check and find the third highest variable by comparing with other elements in an array and find the element and that element should be smaller than second element array

        for (int i = 0; i < arr.length; i++) {
            if(thirdtemp < arr[i] && secondtemp>arr[i]){
                thirdtemp = arr[i];
            }//if
        }//for

        System.out.println("First Highest Value:"+firsttemp);
        System.out.println("Second Highest Value:"+secondtemp);
        System.out.println("Third Highest  Value:"+thirdtemp);

    }//main
}//class
0 голосов
/ 02 июля 2014
public class secondLargestElement 
{
    public static void main(String[] args) 
    {
        int []a1={1,0};
        secondHigh(a1);
    }

    public static void secondHigh(int[] arr)
    {
        try
        {
            int highest,sec_high;
            highest=arr[0];
            sec_high=arr[1];

                for(int i=1;i<arr.length;i++)
                {
                    if(arr[i]>highest)
                    {           
                        sec_high=highest;
                        highest=arr[i]; 
                    }
                    else 
                    // The first condition before the || is to make sure that second highest is not actually same as the highest , think 
                        // about {5,4,5}, you don't want the last  5 to be reported as the sec_high
                        // The other half after || says if the first two elements are same then also replace the sec_high with incoming integer
                        // Think about {5,5,4}
                    if(arr[i]>sec_high && arr[i]<highest || highest==sec_high)
                        sec_high=arr[i];
                }
            //System.out.println("high="+highest +"sec"+sec_high);
            if(highest==sec_high)
                System.out.println("All the elements in the input array are same");
             else
                 System.out.println("The second highest element in the array is:"+ sec_high);

         }

        catch(ArrayIndexOutOfBoundsException e)
        {
        System.out.println("Not enough elements in the array");
        //e.printStackTrace();
        }
    }
}
0 голосов
/ 03 апреля 2014
public class SecondHighest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        /*
         * Find the second largest int item in an unsorted array.
         * This solution assumes we have atleast two elements in the array
         * SOLVED! - Order N. 
         * Other possible solution is to solve with Array.sort and get n-2 element.
         * However, Big(O) time NlgN 
         */

        int[] nums = new int[]{1,2,4,3,5,8,55,76,90,34,91};
        int highest,cur, secondHighest = -1;

        int arrayLength = nums.length;
        highest = nums[1] > nums[0] ? nums[1] : nums[0];
        secondHighest = nums[1] < nums[0] ? nums[1] : nums[0];

        if (arrayLength == 2) {
            System.out.println(secondHighest);

        } else {

            for (int x = 0; x < nums.length; x++) {

                cur = nums[x];
                int tmp;

                if (cur < highest && cur > secondHighest)
                    secondHighest = cur;

                else if (cur > secondHighest && cur > highest) {
                    tmp = highest;
                    highest = cur;
                    secondHighest = tmp;
                }

            }   

            System.out.println(secondHighest);

        }   
    }
}
0 голосов
/ 10 марта 2014

Я предложу еще более короткий и простой ответ на проблему, и он содержит 2 строки кода в методе (требуется import java.util.Arrays):

    public static int secMax(int[] num){
    Arrays.sort(num);
    temp = num[num.length-2];

    return temp;
}
0 голосов
/ 08 января 2014
public static void main(String[] args) {

    int[] arr = {0,12,74,56,2,63,45};
    int f1 = 1, f2 = 0, temp = 0;
    int num = 0;

    for (int i = 0; i < arr.length; i++){
        num = arr[i];
        if (f1 < num) {
            temp = f1;
            f1 = num;
            num = temp;
        }
        if (f2 < num) {
            temp = f2;
            f2 = num;
            num = temp;
        }
    }
    System.out.println("First Highest " + f1 + " Second Highest " + f2 + " Third " + num);

}
0 голосов
/ 20 декабря 2013

Очень просто получить второй по величине элемент в массиве. Я показываю ниже для всех ваших ссылок. Надеюсь, это будет полезно.

import java.util.Arrays;

public class Testdemo {
    public static void main(String[] args) {
    int[] numbers = {1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9};
    Arrays.sort(numbers);
    System.out.println("The second Higest Element :" + numbers[numbers.length-2]);
    }
}

Ответ - Второй Высший Элемент: 8

0 голосов
/ 19 июля 2013

Если вы хотите, чтобы 2-й самый высокий и самый высокий индекс числа в массиве тогда ....

public class Scoller_student {

    public static void main(String[] args) {
        System.out.println("\t\t\tEnter No. of Student\n");
        Scanner scan = new Scanner(System.in);
        int student_no = scan.nextInt();

        // Marks Array.........
        int[] marks;
        marks = new int[student_no];

        // Student name array.....
        String[] names;
        names = new String[student_no];
        int max = 0;
        int sec = max;
        for (int i = 0; i < student_no; i++) {
            System.out.println("\t\t\tEnter Student Name of id = " + i + ".");

            names[i] = scan.next();
            System.out.println("\t\t\tEnter Student Score of id = " + i + ".\n");

            marks[i] = scan.nextInt();
            if (marks[max] < marks[i]) {
                sec = max;
                max = i;
            } else if (marks[sec] < marks[i] && marks[max] != marks[i]) {
                sec = i;
            }
        }

        if (max == sec) {
            sec = 1;
            for (int i = 1; i < student_no; i++) {
                if (marks[sec] < marks[i]) {
                    sec = i;
                }
            }
        }

        System.out.println("\t\t\tHigherst score id = \"" + max + "\" Name : \""
            + names[max] + "\" Max mark : \"" + marks[max] + "\".\n");
        System.out.println("\t\t\tSecond Higherst score id = \"" + sec + "\" Name : \""
            + names[sec] + "\" Max mark : \"" + marks[sec] + "\".\n");

    }
}
0 голосов
/ 04 ноября 2015

Я даю решение, которого нет в JAVA-программе (написано на JavaScript), но требуется и (n / 2) итерация, чтобы найти наибольшее и второе наибольшее число.
Работающая ссылка Fiddler Ссылка Fiddler

 var num=[1020215,2000,35,2,54546,456,2,2345,24,545,132,5469,25653,0,2315648978523];
var j=num.length-1;
var firstHighest=0,seoncdHighest=0;
num[0] >num[num.length-1]?(firstHighest=num[0],seoncdHighest=num[num.length-1]):(firstHighest=num[num.length-1],   seoncdHighest=num[0]);
j--;
for(var i=1;i<=num.length/2;i++,j--)
{
   if(num[i] < num[j] )
   {
          if(firstHighest < num[j]){
          seoncdHighest=firstHighest;
           firstHighest= num[j];
          }
           else if(seoncdHighest < num[j] ) {
               seoncdHighest= num[j];

           }
   }
   else {
       if(firstHighest < num[i])
       {
           seoncdHighest=firstHighest;
           firstHighest= num[i];

       }
       else if(seoncdHighest < num[i] ) {
            seoncdHighest= num[i];

       }
   }

}         
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...