java 在Java中显示数组中的第二大数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10716186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:14:56  来源:igfitidea点击:

Display Second Largest no in Array in Java

javaarrays

提问by Dipu

Hi all I want to find out second Largest no in Array accept negative numbers. I have used following code and this display second largest no of only positive no.So please suggest me how to do this.

大家好,我想找出数组中的第二大数字接受负数。我使用了以下代码,并且此显示第二大编号,只有正编号。所以请建议我如何执行此操作。

class ArrayExample {
    public static void main(String[] args) {
        int secondlargest = 0;
        int largest = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter array values: ");
        int arr[] = new int[5];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = input.nextInt();
            if (largest < arr[i]) {
                secondlargest = largest;
                largest = arr[i];
            }
            if (secondlargest < arr[i] && largest != arr[i])
                secondlargest = arr[i];
        }
        System.out.println("Second Largest number is: " + secondlargest);
    }
}

采纳答案by Jainendra

Initialize the variables secondlargestand largestwith the smallest negative values.
Use this code:

初始化变量secondlargest,并largest用最小的负值。
使用此代码:

class ArrayExample {
        public static void main(String[] args) {
            int secondlargest = Integer.MIN_VALUE;
            int largest = Integer.MIN_VALUE;
            Scanner input = new Scanner(System.in);
            System.out.println("Enter array values: ");
            int arr[] = new int[5];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = input.nextInt();
                if (largest < arr[i]) {
                    secondlargest = largest;
                    largest = arr[i];
                }
                if (secondlargest < arr[i] && largest != arr[i])
                    secondlargest = arr[i];
            }
            System.out.println("Second Largest number is: " + secondlargest);
        }
    }

回答by alegen

The problem comes from the fact that you initialize your two variables to 0 in the lines:

问题来自于您在行中将两个变量初始化为 0 的事实:

int secondlargest = 0;
int largest = 0;

You should instead initialize them to Integer.MIN_VALUEand then it will also work for negative values.

您应该改为将它们初始化为Integer.MIN_VALUE,然后它也适用于负值。

回答by Hakan Serce

Initialize largest and secondLargest to Integer.MIN_VALUEinstead of zero.

将 maximum 和 secondLargest 初始化为Integer.MIN_VALUE而不是零。

回答by óscar López

This works for me, for both positive and negative values. Before the loop, you need to initialize the largestand secondlargestvariables with very small values, by doing this you can be (almost) sure that all the other values in the array will be greater than them:

这对我有用,适用于正值和负值。在循环之前,您需要用非常小的值初始化largestsecondlargest变量,通过这样做,您可以(几乎)确定数组中的所有其他值都将大于它们:

int largest = Integer.MIN_VALUE;
int secondlargest = Integer.MIN_VALUE;

Inside the loop:

循环内:

if (arr[i] > largest) {
    secondlargest = largest;
    largest = arr[i];
}

else if (arr[i] != largest && arr[i] > secondlargest) {
    secondlargest = arr[i];
}

After the loop:

循环后:

if (secondlargest != Integer.MIN_VALUE)
    System.out.println("Second Largest number is: " + secondlargest);

Notice that the last check is required for the (rather unlikely) case where all the elements in the array happen to be Integer.MIN_VALUE.

请注意,对于数组中的所有元素恰好是Integer.MIN_VALUE.

回答by Ravi Teja N

I think this method may be useful it takes around n+log(n)-2 comparisons

我认为这种方法可能很有用,它需要进行 n+log(n)-2 次比较

 import java.util.ArrayList;


 public class SecondLargest {
 static ArrayList<ArrayList<Integer>> level = new ArrayList<ArrayList<Integer>>();

public static void main(String[] args) {
    int input[]={9,8,7,4,5,6,1,2,3,1,1,21,33,32,1,2,3,12,3,2,1};
    ArrayList<Integer> arr= new ArrayList<Integer>();

    for(int i=0;i<input.length;i++){
        arr.add(input[i]);
    }
    level.add(arr);
    seconLarger(arr);
    System.out.println(SecondLarge(level));
}

private static ArrayList<Integer> seconLarger(ArrayList<Integer> arr) {
    ArrayList<Integer> tmp= new ArrayList<Integer>();
    if (arr.size()==1)
    {
        return arr;
    }

if(arr.size()%2==0)
    {
        for(int i=0;i<arr.size();i=i+2)
        {
            if(arr.get(i)>arr.get(i+1))
            {
                tmp.add(arr.get(i));
            }
            else
            {
                tmp.add(arr.get(i+1));
            }
        }


    }   
else 
    {
        for(int i=0;i<arr.size()-1;i=i+2)
        {
            if(arr.get(i)>arr.get(i+1))
            {
                tmp.add(arr.get(i));
            }
            else
            {
                tmp.add(arr.get(i+1));
            }
        }
        tmp.add(arr.get(arr.size()-1));
    }
level.add(tmp);
return seconLarger(tmp);
}

private static int SecondLarge(ArrayList<ArrayList<Integer>> li)
{
    int li_size=li.size();
    int large=li.get(li_size-1).get(0);
    int secondlarge=0;
    int tmp=0;
    for(int i=li_size-2;i>=0;i--)
    {
        ArrayList<Integer> arr = li.get(i);
        if(large==arr.get(tmp))
        {
            if(tmp+1<arr.size())
            {
                if(secondlarge<arr.get(tmp+1))
                {
                    secondlarge=arr.get(tmp+1);
                }
            }
        }
        else
        {
            if(secondlarge<arr.get(tmp))
            {
                secondlarge=arr.get(tmp);
            }
            tmp=tmp+1;

        }

        tmp=tmp*2;
    }
    return secondlarge;
}}

回答by Cyruses Cyrus

package com.demo.mum;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author cyruses
 * 
 */
public class SecondLargest {
    public static int largest = Integer.MIN_VALUE;
    public static int secondLargest = Integer.MIN_VALUE;

    public static void main(String args[]) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the Size of Array:");
        int n = Integer.parseInt(br.readLine());
        int a[] = new int[n];
        System.out.println("Enter the elements on array:");
        for (int i = 0; i < a.length; i++) {
            a[i] = Integer.parseInt(br.readLine());
        }
        System.out.println("Elements you entered are:");
        for (int i = 0; i < a.length; i++) {
            System.out.println("a[" + i + "]" + "=" + a[i]);
        }
        if (a.length <= 2) {
            if (a[0] == a[1]) {
                System.out.println("Theres no second largest number in your array");
            } else {
                System.out.println("SecondLargest:" + secondLargest(a));
            }
        } else {
            System.out.println("SecondLargest:" + secondLargest(a));
        }
    }

    private static int secondLargest(int[] a) {

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

回答by rocketboy

Or here is a gimmicky Java implementation which doesn't rely on Integer.MIN_VALUE

或者这里是一个不依赖于 Integer.MIN_VALUE 的花哨的 Java 实现

int findSecondHighest(int[] arr){
    if(arr == null || arr.length < 2){
        throw new IllegalArgumentException();
    }

    int fh,sh;

    if(arr[0]>=arr[1]){
        fh = arr[0];
        sh = arr[1];
    }else{
        fh = arr[1];
        sh = arr[0];
    }

    for (int i = 2; i < arr.length; i++) {
        if(fh < arr[i]){
            sh = fh;
            fh = arr[i];
        }else if(sh < arr[i]){
            sh = arr[i];
        }
    }

    return sh;
}

回答by manohar e

Instead of initializing the second largest number to min value or zero. You can follow below code to get second largest number.

而不是将第二大数字初始化为最小值或零。您可以按照以下代码获得第二大数字。

import java.util.Scanner;

public class SecondLargestNumber {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] a;
        int n;
        System.out.println("Enter number of elements");
        n = scanner.nextInt();
        a = new int[n];
        for(int i=0; i<n; i++) {
            a[i] = scanner.nextInt();
        }
        int secondLargestNumber = a[0];
        int largestNumber = a[0];
        int count = 1;
        for(int i=1; i<a.length; i++) {
            if(a[i] >= largestNumber) {
                if(a[i] == largestNumber) {
                    count++;
                } else {
                    count = 1;
                }
                secondLargestNumber = largestNumber;
                largestNumber = a[i];
            } else {
                if(secondLargestNumber == largestNumber && count == 1) {
                    secondLargestNumber = a[i];
                } else if(a[i] > secondLargestNumber) {
                    secondLargestNumber = a[i];
                }
            }
        }
        System.out.println("Second Largest Number: " + secondLargestNumber);
    }
}

回答by girish

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.println("Enter array size = ");
    int size=in.nextInt();
    int[] n = new int[size];
    System.out.println("Enter "+ size +" values ");

    for(int i=0;i<n.length;i++)
        n[i] = in.nextInt();
    int big=n[0],sbig=n[0];

    // finding big, second big
    for(int i=0;i<n.length;i++){
        if(big<n[i]){
            sbig=big;
            big=n[i];
            }else if(sbig<n[i])
                sbig=n[i];
    }
    // finding second big if first element itself big
    if(big==n[0]){
        sbig=n[1];
        for(int i=1;i<n.length;i++){
            if(sbig<n[i]){
                sbig=n[i];
                }
        }
    }       

    System.out.println("Big "+ big+" sBig "+ sbig);

    in.close();
}