I'm having difficulty to understand the logic behind the method to find the second highest number in array. The method used is to find the highest in the array but less than the previous highest (which has already been found). The thing that I still can't figure it out is why || highest_score == second_highest
is necessary. For example I input three numbers: 98, 56, 3. Without it, both highest and second highest would be 98. Please explain.
我很难理解该方法背后的逻辑,以找到数组中第二个最高的数字。所使用的方法是在数组中找到最高的,但比之前的最高(已经找到)。我仍然不知道为什么|| highest_score == second_top是必要的。例如,我输入三个数字: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];
38 个解决方案
#1
29
I'm not convinced that doing what you did fixes the problem; I think it masks yet another problem in your logic. To find the second highest is actually quite simple:
我不相信做你所做的解决了问题;我认为它掩盖了你逻辑中的另一个问题。发现第二高其实相当简单:
static int secondHighest(int... nums) {
int high1 = Integer.MIN_VALUE;
int high2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > high1) {
high2 = high1;
high1 = num;
} else if (num > high2) {
high2 = num;
}
}
return high2;
}
This is O(N)
in one pass. If you want to accept ties, then change to if (num >= high1)
, but as it is, it will return Integer.MIN_VALUE
if there aren't at least 2 elements in the array. It will also return Integer.MIN_VALUE
if the array contains only the same number.
这是O(N)一次。如果您想要接受连接,那么可以更改为If (num >= high1),但是它是,它将返回整数。如果数组中没有至少两个元素,则MIN_VALUE。它也会返回整数。如果数组只包含相同的数字,则MIN_VALUE。
#2
11
// Initialize these to the smallest value possible
int highest = Integer.MIN_VALUE;
int secondHighest = Integer.MIN_VALUE;
// Loop over the array
for (int i = 0; i < array.Length; i++) {
// If we've found a new highest number...
if (array[i] > highest) {
// ...shift the current highest number to second highest
secondHighest = highest;
// ...and set the new highest.
highest = array[i];
} else if (array[i] > secondHighest)
// Just replace the second highest
secondHighest = array[i];
}
}
// After exiting the loop, secondHighest now represents the second
// largest value in the array
Edit:
Whoops. Thanks for pointing out my mistake, guys. Fixed now.#3
5
If the first element which second_highest is set to initially is already the highest element, then it should be reassigned to a new element when the next element is found. That is, it's being initialized to 98, and should be set to 56. But, 56 isn't higher than 98, so it won't be set unless you do the check.
如果第一个元素在第一个元素中被设置为最初的元素,那么当找到下一个元素时,它应该被重新分配到一个新元素中。也就是说,它被初始化为98,应该设置为56。但是,56并不比98高,所以除非你做检查,否则它不会被设置。
If the highest number appears twice, this will result in the second highest value as opposed to the second element that you would find if you sorted the array.
如果最高的数字出现两次,这将会导致第二个最大值,而不是第二个元素,如果您对数组进行排序,则会发现第二个元素。
#4
1
public static int secondLargest(int[] input) {
int largest,secondLargest;
if(input[0] > input[1]) {
largest = input[0];
secondLargest = input[1];
}
else {
largest = input[1];
secondLargest = input[0];
}
for(int i = 2; i < input.length; i++) {
if((input[i] <= largest) && input[i] > secondLargest) {
secondLargest = input[i];
}
if(input[i] > largest) {
secondLargest = largest;
largest = input[i];
}
}
return secondLargest;
}
#5
1
The answers I saw wont work if there are two same largest numbers like the below example.
如果有两个相同的最大的数字,比如下面的例子,我看到的答案不会起作用。
int[] randomIntegers = { 1, 5, 4, 2, 8, 1, 8, 9,9 };
SortedSet<Integer> set = new TreeSet<Integer>();
for (int i: randomIntegers) {
set.add(i);
}
// Remove the maximum value; print the largest remaining item
set.remove(set.last());
System.out.println(set.last());
I have removed it from the Set not from the Array
我已经把它从数组中删除了。
#6
1
public class SecondLargestNumberInArray
{
public static void main(String[] args)
{
int arr[] = {99, 76, 47, 85, 929, 52, 48, 36, 66, 81,9};
int largest = arr[0];
int secondLargest = arr[0];
System.out.println("The given array is:" );
boolean find=false;
boolean flag=true;
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]+"\t");
}
System.out.println("");
while(flag)
{
for (int i = 0; i < arr.length; i++)
{
if (arr[i] > largest)
{
find=true;
secondLargest = largest;
largest = arr[i];
}
else if (arr[i] > secondLargest)
{
find=true;
secondLargest = arr[i];
}
}
if(find)
{
System.out.println("\nSecond largest number is:" + secondLargest);
flag=false;
}else
{
largest = arr[1];
secondLargest = arr[1];
}
}
}
}
Output is
The given array is:
99 76 47 85 929 52 48 36 66 81 9
Second largest number is: -> 99
#7
1
My idea is that you assume that first and second members of the array are your first max and second max. Then you take each new member of an array and compare it with the 2nd max. Don't forget to compare 2nd max with the 1st one. If it's bigger, just swap them.
我的想法是,你假设数组的第一个和第二个成员是你的第一个max和第二个max。然后将数组中的每个新成员与第二个max进行比较。别忘了把第二个max和第一个比较。如果它更大,就交换它们。
public static int getMax22(int[] arr){
int max1 = arr[0];
int max2 = arr[1];
for (int i = 2; i < arr.length; i++){
if (arr[i] > max2)
{
max2 = arr[i];
}
if (max2 > max1)
{
int temp = max1;
max1 = max2;
max2 = temp;
}
}
return max2;
}
#8
0
If time complexity is not an issue, then You can run bubble sort and within two iterations, you will get your second highest number because in the first iteration of the loop, the largest number will be moved to the last. In the second iteration, the second largest number will be moved next to last.
如果时间复杂度不是问题,那么您可以运行冒泡排序,在两个迭代中,您将获得第二个最高的数字,因为在循环的第一次迭代中,最大的数字将被移动到最后一个。在第二次迭代中,第二个最大的数将被移动到最后一个。
#9
0
If you want to 2nd highest and highest number index in array then....
如果你想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");
}
}
#10
0
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();
}
}
}
#11
0
You can find Largest and Third largest number of unsorted array as well.
你也可以找到最大和第三大的无序数组。
public class ThirdLargestNumber {
public static void main(String[] args) {
int arr[] = { 220, 200, 100, 100, 300, 600, 50, 5000, 125, 785 };
int first = 0, second = 0, third = 0, firstTemp = 0, secondTemp = 0;
for (int i = 0; i <= 9 /*
* Length of array-1. You can use here length
* property of java array instead of hard coded
* value
*/; i++) {
if (arr[i] == first) {
continue;
}
if (arr[i] > first) {
firstTemp = first;
secondTemp = second;
first = arr[i];
second = firstTemp;
if (secondTemp > third) {
third = secondTemp;
}
} else {
if ((arr[i] == second) || (arr[i]) == first) {
continue;
}
if ((arr[i] > second) && (arr[i]) < first) {
secondTemp = second;
second = arr[i];
if (secondTemp > third) {
third = secondTemp;
}
} else {
if (arr[i] > third) {
third = arr[i];
}
}
}
}
// System.out.println("Third largest number: " + third);
System.out.println("Second largest number: " + second);
// System.out.println("Largest number: " + first);
}
}
#12
0
I am giving solution that's not in JAVA program (written in JavaScript), but it takes o(n/2) iteration to find the highest and second highest number.
Working fiddler link Fiddler link
我给出的解决方案不是JAVA程序(用JavaScript编写的),而是用o(n/2)迭代来找到最高和第二高的数字。使用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];
}
}
}
#13
0
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
#14
0
If this question is from the interviewer then please DONT USE SORTING Technique or Don't use any built in methods like Arrays.sort or Collection.sort. The purpose of this questions is how optimal your solution is in terms of performance so the best option would be just implement with your own logic with O(n-1) implementation. The below code is strictly for beginners and not for experienced guys.
如果这个问题来自于面试官,那么请不要使用分拣技术,也不要使用像数组那样的方法。或Collection.sort排序。这个问题的目的是,在性能方面,您的解决方案是多么的理想,所以最好的选择是用您自己的逻辑与O(n-1)实现来实现。下面的代码是针对初学者的,而不是针对有经验的人的。
public void printLargest(){
int num[] ={ 900,90,6,7,5000,4,60000,20,3};
int largest = num[0];
int secondLargest = num[1];
for (int i=1; i<num.length; i++)
{
if(largest < num[i])
{
secondLargest = largest;
largest = num[i];
}
else if(secondLargest < num[i]){
secondLargest = num[i];
}
}
System.out.println("Largest : " +largest);
System.out.println("Second Largest : "+secondLargest);
}
#15
0
Problem: The problem is to get the second largest array element.
问题:问题是获取第二大数组元素。
Observation: Second largest number is defined as the number that has the minimum difference when subtracted from the maximum element in the array.
观察:第二大数字被定义为当从数组的最大元素中减去最小值时的最小值。
Solution: This is a two pass solution. First pass is to find the maximum number. Second pass is to find the element that has minimum difference with the maximum element as compared to other array elements. Example: In the array [2, 3, 6, 6, 5] maximum = 6 and second maximum = 5 , since it has the minimum difference to the maximum element 6 - 5 = 1 the solution for second largest = 5
解决方案:这是一个两个通过的解决方案。第一步是找到最大的数。第二遍是查找与其他数组元素相比,与最大元素有最小差异的元素。例:在数组中[2,3,6,6,5]最大值= 6和第2个最大值= 5,因为它对最大元素6 - 5 = 1的最小差值为5 = 1。
function printSecondMax(myArray) {
var x, max = myArray[0];
// Find maximum element
for(x in myArray){
if(max < myArray[x]){
max = myArray[x];
}
}
var secondMax = myArray[0], diff = max - secondMax;
// Find second max, an element that has min diff with the max
for(x in myArray){
if(diff != 0 && (max - myArray[x]) != 0 && diff > (max - myArray[x])){
secondMax = myArray[x];
diff = max - secondMax;
}
}
console.log(secondMax);
}
Complexity : O(n), This is the simplest way to do this.
复杂度:O(n),这是最简单的方法。
For finding maximum element even more efficiently one can look into max heap, a call to max-heapify will take O(log n) time to find the max and then pop-ing the top element gives maximum. To get the second maximum, max-heapify after pop-ing the top and keep pop-ing till you get a number that is less than maximum. That will be the second maximum. This solution has O(n log n) complexity.
为了更有效地找到最大元素,我们可以查看max heap,调用max-heapify将需要O(log n)时间来找到max,然后将top元素的poping形式最大化。为了获得第二个最大值,在弹出顶部后,max-heapify一直保持poping直到你得到一个小于最大值的数字。这将是第二个最大值。这个解有O(n log n)的复杂度。
#16
0
private static int SecondBiggest(int[] vector)
{
if (vector == null)
{
throw new ArgumentNullException("vector");
}
if (vector.Length < 2)
{
return int.MinValue;
}
int max1 = vector[0];
int max2 = vector[1];
for (int i = 2; i < vector.Length; ++i)
{
if (max1 > max2 && max1 != vector[i])
{
max2 = Math.Max(max2, vector[i]);
}
else if (max2 != vector[i])
{
max1 = Math.Max(max1, vector[i]);
}
}
return Math.Min(max1, max2);
}
This treats duplicates as the same number. You can change the condition checks if you want to all the biggest and the second biggest to be duplicates.
这个处理重复的数字是相同的。您可以更改条件检查,如果您想要所有最大的和第二大的是重复的。
#17
0
Please try this one: Using this method, You can fined second largest number in array even array contain random number. The first loop is used to solve the problem if largest number come first index of array.
请试试这个:使用这个方法,你可以对数组中的第二大数字进行罚款,即使数组包含随机数。第一个循环被用来解决最大的数字是数组的第一个索引。
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);
}
}
#18
0
public class SecondHighInIntArray {
公开课SecondHighInIntArray {
public static void main(String[] args) {
int[] intArray=new int[]{2,2,1};
//{2,2,1,12,3,7,9,-1,-5,7};
int secHigh=findSecHigh(intArray);
System.out.println(secHigh);
}
private static int findSecHigh(int[] intArray) {
int highest=Integer.MIN_VALUE;
int sechighest=Integer.MIN_VALUE;
int len=intArray.length;
for(int i=0;i<len;i++)
{
if(intArray[i]>highest)
{
sechighest=highest;
highest=intArray[i];
continue;
}
if(intArray[i]<highest && intArray[i]>sechighest)
{
sechighest=intArray[i];
continue;
}
}
return sechighest;
}
}
}
#19
0
Second Largest in O(n/2)
第二大的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;
}
}
}
}
}
#20
0
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);
}
}
}
#21
0
Use following function
`
使用以下函数”
public static int secHigh(int arr[]){
int firstHigh = 0,secHigh = 0;
for(int x: arr){
if(x > firstHigh){
secHigh = firstHigh;
firstHigh = x;
}else if(x > secHigh){
secHigh = x;
}
}
return secHigh;
}
Function Call
函数调用
int secondHigh = secHigh(arr);
#22
0
import java.util.Scanner;
public class SecondLargest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter size of array : ");
int n = sc.nextInt();
int ar[] = new int[n];
for(int i=0;i<n;i++)
{
System.out.print("Enter value for array : ");
ar[i] = sc.nextInt();
}
int m=ar[0],m2=ar[0];
for(int i=0;i<n;i++)
{
if(ar[i]>m)
m=ar[i];
}
for(int i=0;i<n;i++)
{
if(ar[i]>m2 && ar[i]<m)
m2=ar[i];
}
System.out.println("Second largest : "+m2);
sc.close();
}
}
#23
0
public void findMax(int a[]) {
int large = Integer.MIN_VALUE;
int secondLarge = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
if (large < a[i]) {
secondLarge = large;
large = a[i];
} else if (a[i] > secondLarge) {
if (a[i] != large) {
secondLarge = a[i];
}
}
}
System.out.println("Large number " + large + " Second Large number " + secondLarge);
}
The above code has been tested with integer arrays having duplicate entries, negative values. Largest number and second largest number are retrived in one pass. This code only fails if array only contains multiple copy of same number like {8,8,8,8} or having only one number.
上面的代码已经用整数数组进行了测试,其中包含了重复项、负值。最大的数和第二大的数在一次传递中被检索。如果数组只包含相同数字的多个副本,如{8、8、8}或只有一个数字,则此代码只会失败。
#24
0
public class SecondLargestNumber
{
public static void main(String[] args)
{
int[] var={-11,-11,-11,-11,115,-11,-9};
int largest = 0;
int secLargest = 0;
if(var.length == 1)
{
largest = var[0];
secLargest = var[0];
}
else if(var.length > 1)
{
largest= var[0];
secLargest = var[1];
for(int i=1;i<var.length;i++)
{
if(secLargest!=largest)
{
if(var[i]>largest)
{
secLargest = largest;
largest = var[i];
}
else if(var[i]>secLargest && var[i] != largest)
{
secLargest= var[i];
}
}
else
{
if(var[i]>largest)
{
secLargest = largest;
largest = var[i];
}
else
{
secLargest = var[i];
}
}
}
}
System.out.println("Largest: "+largest+" Second Largest: "+secLargest);
}
}
#25
0
/* Function to print the second largest elements */
void print2largest(int arr[], int arr_size)
{
int i, first, second;
/* There should be atleast two elements */
if (arr_size < 2)
{
printf(" Invalid Input ");
return;
}
first = second = INT_MIN;
for (i = 0; i < arr_size ; i ++)
{
/* If current element is smaller than first
then update both first and second */
if (arr[i] > first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between first and
second then update second */
else if (arr[i] > second && arr[i] != first)
second = arr[i];
}
if (second == INT_MIN)
printf("There is no second largest elementn");
else
printf("The second largest element is %dn", second);
}
#26
0
I have got the simplest logic to find the second largest number may be, it's not. The logic find sum of two number in the array which has the highest value and then check which is greater among two simple............
我有一个最简单的逻辑来找到第二个最大的数,它不是。逻辑在数组中找到两个数字的和,它具有最高的值,然后在两个简单的运算符中检查哪个更大……
int ar[]={611,4,556,107,5,55,811};
int sum=ar[0]+ar[1];
int temp=0;
int m=ar[0];
int n=ar[1];
for(int i=0;i<ar.length;i++){
for(int j=i;j<ar.length;j++){
if(i!=j){
temp=ar[i]+ar[j];
if(temp>sum){
sum=temp;
m=ar[i];
n=ar[j];
}
temp=0;
}
}
}
if(m>n){
System.out.println(n);
}
else{
System.out.println(m);
}
#27
0
import java.util.Scanner;
进口java.util.Scanner;
public class SecondHighestFromArrayTest {
公开课SecondHighestFromArrayTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter size of Array");
int size = scan.nextInt();
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = scan.nextInt();
}
System.out.println("second highest element " + getSecondHighest(arr));
}
public static int getSecondHighest(int arr[]) {
int firstHighest = arr[0];
int secondHighest = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > firstHighest) {
secondHighest = firstHighest;
firstHighest = arr[i];
} else if (arr[i] > secondHighest) {
secondHighest = arr[i];
}
}
return secondHighest;
}
}
}
#28
0
The simplest way is -
最简单的方法是-。
public class SecondLargest {
public static void main(String[] args) {
int[] arr = { 1, 2, 5, 6, 3 };
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
// If current element is smaller than first then update both first
// and second
if (arr[i] > first) {
second = first;
first = arr[i];
}
// If arr[i] is in between first and second then update second
else if (arr[i] > second && arr[i] != first) {
second = arr[i];
}
}
}
}
#29
-1
Its very easy to get the 2nd highest element in an array. I've shows below for all your reference. Hope this will be helpful.
它很容易得到数组中的第二高元素。我已经在下面展示了你所有的参考资料。希望这对你有帮助。
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]);
}
}
Ans - The second Higest Element :8
Ans -第2个最复杂的元素:8。
#30
-1
I will propose even shorter and simplest answer to the problem and it contains 2 lines of code in the method (import java.util.Arrays
is required):
我将对这个问题提出更简短和最简单的答案,它包含了方法中的两行代码(导入java.util)。数组是必需的):
public static int secMax(int[] num){
Arrays.sort(num);
temp = num[num.length-2];
return temp;
}
#1
29
I'm not convinced that doing what you did fixes the problem; I think it masks yet another problem in your logic. To find the second highest is actually quite simple:
我不相信做你所做的解决了问题;我认为它掩盖了你逻辑中的另一个问题。发现第二高其实相当简单:
static int secondHighest(int... nums) {
int high1 = Integer.MIN_VALUE;
int high2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > high1) {
high2 = high1;
high1 = num;
} else if (num > high2) {
high2 = num;
}
}
return high2;
}
This is O(N)
in one pass. If you want to accept ties, then change to if (num >= high1)
, but as it is, it will return Integer.MIN_VALUE
if there aren't at least 2 elements in the array. It will also return Integer.MIN_VALUE
if the array contains only the same number.
这是O(N)一次。如果您想要接受连接,那么可以更改为If (num >= high1),但是它是,它将返回整数。如果数组中没有至少两个元素,则MIN_VALUE。它也会返回整数。如果数组只包含相同的数字,则MIN_VALUE。
#2
11
// Initialize these to the smallest value possible
int highest = Integer.MIN_VALUE;
int secondHighest = Integer.MIN_VALUE;
// Loop over the array
for (int i = 0; i < array.Length; i++) {
// If we've found a new highest number...
if (array[i] > highest) {
// ...shift the current highest number to second highest
secondHighest = highest;
// ...and set the new highest.
highest = array[i];
} else if (array[i] > secondHighest)
// Just replace the second highest
secondHighest = array[i];
}
}
// After exiting the loop, secondHighest now represents the second
// largest value in the array
Edit:
Whoops. Thanks for pointing out my mistake, guys. Fixed now.#3
5
If the first element which second_highest is set to initially is already the highest element, then it should be reassigned to a new element when the next element is found. That is, it's being initialized to 98, and should be set to 56. But, 56 isn't higher than 98, so it won't be set unless you do the check.
如果第一个元素在第一个元素中被设置为最初的元素,那么当找到下一个元素时,它应该被重新分配到一个新元素中。也就是说,它被初始化为98,应该设置为56。但是,56并不比98高,所以除非你做检查,否则它不会被设置。
If the highest number appears twice, this will result in the second highest value as opposed to the second element that you would find if you sorted the array.
如果最高的数字出现两次,这将会导致第二个最大值,而不是第二个元素,如果您对数组进行排序,则会发现第二个元素。
#4
1
public static int secondLargest(int[] input) {
int largest,secondLargest;
if(input[0] > input[1]) {
largest = input[0];
secondLargest = input[1];
}
else {
largest = input[1];
secondLargest = input[0];
}
for(int i = 2; i < input.length; i++) {
if((input[i] <= largest) && input[i] > secondLargest) {
secondLargest = input[i];
}
if(input[i] > largest) {
secondLargest = largest;
largest = input[i];
}
}
return secondLargest;
}
#5
1
The answers I saw wont work if there are two same largest numbers like the below example.
如果有两个相同的最大的数字,比如下面的例子,我看到的答案不会起作用。
int[] randomIntegers = { 1, 5, 4, 2, 8, 1, 8, 9,9 };
SortedSet<Integer> set = new TreeSet<Integer>();
for (int i: randomIntegers) {
set.add(i);
}
// Remove the maximum value; print the largest remaining item
set.remove(set.last());
System.out.println(set.last());
I have removed it from the Set not from the Array
我已经把它从数组中删除了。
#6
1
public class SecondLargestNumberInArray
{
public static void main(String[] args)
{
int arr[] = {99, 76, 47, 85, 929, 52, 48, 36, 66, 81,9};
int largest = arr[0];
int secondLargest = arr[0];
System.out.println("The given array is:" );
boolean find=false;
boolean flag=true;
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]+"\t");
}
System.out.println("");
while(flag)
{
for (int i = 0; i < arr.length; i++)
{
if (arr[i] > largest)
{
find=true;
secondLargest = largest;
largest = arr[i];
}
else if (arr[i] > secondLargest)
{
find=true;
secondLargest = arr[i];
}
}
if(find)
{
System.out.println("\nSecond largest number is:" + secondLargest);
flag=false;
}else
{
largest = arr[1];
secondLargest = arr[1];
}
}
}
}
Output is
The given array is:
99 76 47 85 929 52 48 36 66 81 9
Second largest number is: -> 99
#7
1
My idea is that you assume that first and second members of the array are your first max and second max. Then you take each new member of an array and compare it with the 2nd max. Don't forget to compare 2nd max with the 1st one. If it's bigger, just swap them.
我的想法是,你假设数组的第一个和第二个成员是你的第一个max和第二个max。然后将数组中的每个新成员与第二个max进行比较。别忘了把第二个max和第一个比较。如果它更大,就交换它们。
public static int getMax22(int[] arr){
int max1 = arr[0];
int max2 = arr[1];
for (int i = 2; i < arr.length; i++){
if (arr[i] > max2)
{
max2 = arr[i];
}
if (max2 > max1)
{
int temp = max1;
max1 = max2;
max2 = temp;
}
}
return max2;
}
#8
0
If time complexity is not an issue, then You can run bubble sort and within two iterations, you will get your second highest number because in the first iteration of the loop, the largest number will be moved to the last. In the second iteration, the second largest number will be moved next to last.
如果时间复杂度不是问题,那么您可以运行冒泡排序,在两个迭代中,您将获得第二个最高的数字,因为在循环的第一次迭代中,最大的数字将被移动到最后一个。在第二次迭代中,第二个最大的数将被移动到最后一个。
#9
0
If you want to 2nd highest and highest number index in array then....
如果你想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");
}
}
#10
0
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();
}
}
}
#11
0
You can find Largest and Third largest number of unsorted array as well.
你也可以找到最大和第三大的无序数组。
public class ThirdLargestNumber {
public static void main(String[] args) {
int arr[] = { 220, 200, 100, 100, 300, 600, 50, 5000, 125, 785 };
int first = 0, second = 0, third = 0, firstTemp = 0, secondTemp = 0;
for (int i = 0; i <= 9 /*
* Length of array-1. You can use here length
* property of java array instead of hard coded
* value
*/; i++) {
if (arr[i] == first) {
continue;
}
if (arr[i] > first) {
firstTemp = first;
secondTemp = second;
first = arr[i];
second = firstTemp;
if (secondTemp > third) {
third = secondTemp;
}
} else {
if ((arr[i] == second) || (arr[i]) == first) {
continue;
}
if ((arr[i] > second) && (arr[i]) < first) {
secondTemp = second;
second = arr[i];
if (secondTemp > third) {
third = secondTemp;
}
} else {
if (arr[i] > third) {
third = arr[i];
}
}
}
}
// System.out.println("Third largest number: " + third);
System.out.println("Second largest number: " + second);
// System.out.println("Largest number: " + first);
}
}
#12
0
I am giving solution that's not in JAVA program (written in JavaScript), but it takes o(n/2) iteration to find the highest and second highest number.
Working fiddler link Fiddler link
我给出的解决方案不是JAVA程序(用JavaScript编写的),而是用o(n/2)迭代来找到最高和第二高的数字。使用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];
}
}
}
#13
0
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
#14
0
If this question is from the interviewer then please DONT USE SORTING Technique or Don't use any built in methods like Arrays.sort or Collection.sort. The purpose of this questions is how optimal your solution is in terms of performance so the best option would be just implement with your own logic with O(n-1) implementation. The below code is strictly for beginners and not for experienced guys.
如果这个问题来自于面试官,那么请不要使用分拣技术,也不要使用像数组那样的方法。或Collection.sort排序。这个问题的目的是,在性能方面,您的解决方案是多么的理想,所以最好的选择是用您自己的逻辑与O(n-1)实现来实现。下面的代码是针对初学者的,而不是针对有经验的人的。
public void printLargest(){
int num[] ={ 900,90,6,7,5000,4,60000,20,3};
int largest = num[0];
int secondLargest = num[1];
for (int i=1; i<num.length; i++)
{
if(largest < num[i])
{
secondLargest = largest;
largest = num[i];
}
else if(secondLargest < num[i]){
secondLargest = num[i];
}
}
System.out.println("Largest : " +largest);
System.out.println("Second Largest : "+secondLargest);
}
#15
0
Problem: The problem is to get the second largest array element.
问题:问题是获取第二大数组元素。
Observation: Second largest number is defined as the number that has the minimum difference when subtracted from the maximum element in the array.
观察:第二大数字被定义为当从数组的最大元素中减去最小值时的最小值。
Solution: This is a two pass solution. First pass is to find the maximum number. Second pass is to find the element that has minimum difference with the maximum element as compared to other array elements. Example: In the array [2, 3, 6, 6, 5] maximum = 6 and second maximum = 5 , since it has the minimum difference to the maximum element 6 - 5 = 1 the solution for second largest = 5
解决方案:这是一个两个通过的解决方案。第一步是找到最大的数。第二遍是查找与其他数组元素相比,与最大元素有最小差异的元素。例:在数组中[2,3,6,6,5]最大值= 6和第2个最大值= 5,因为它对最大元素6 - 5 = 1的最小差值为5 = 1。
function printSecondMax(myArray) {
var x, max = myArray[0];
// Find maximum element
for(x in myArray){
if(max < myArray[x]){
max = myArray[x];
}
}
var secondMax = myArray[0], diff = max - secondMax;
// Find second max, an element that has min diff with the max
for(x in myArray){
if(diff != 0 && (max - myArray[x]) != 0 && diff > (max - myArray[x])){
secondMax = myArray[x];
diff = max - secondMax;
}
}
console.log(secondMax);
}
Complexity : O(n), This is the simplest way to do this.
复杂度:O(n),这是最简单的方法。
For finding maximum element even more efficiently one can look into max heap, a call to max-heapify will take O(log n) time to find the max and then pop-ing the top element gives maximum. To get the second maximum, max-heapify after pop-ing the top and keep pop-ing till you get a number that is less than maximum. That will be the second maximum. This solution has O(n log n) complexity.
为了更有效地找到最大元素,我们可以查看max heap,调用max-heapify将需要O(log n)时间来找到max,然后将top元素的poping形式最大化。为了获得第二个最大值,在弹出顶部后,max-heapify一直保持poping直到你得到一个小于最大值的数字。这将是第二个最大值。这个解有O(n log n)的复杂度。
#16
0
private static int SecondBiggest(int[] vector)
{
if (vector == null)
{
throw new ArgumentNullException("vector");
}
if (vector.Length < 2)
{
return int.MinValue;
}
int max1 = vector[0];
int max2 = vector[1];
for (int i = 2; i < vector.Length; ++i)
{
if (max1 > max2 && max1 != vector[i])
{
max2 = Math.Max(max2, vector[i]);
}
else if (max2 != vector[i])
{
max1 = Math.Max(max1, vector[i]);
}
}
return Math.Min(max1, max2);
}
This treats duplicates as the same number. You can change the condition checks if you want to all the biggest and the second biggest to be duplicates.
这个处理重复的数字是相同的。您可以更改条件检查,如果您想要所有最大的和第二大的是重复的。
#17
0
Please try this one: Using this method, You can fined second largest number in array even array contain random number. The first loop is used to solve the problem if largest number come first index of array.
请试试这个:使用这个方法,你可以对数组中的第二大数字进行罚款,即使数组包含随机数。第一个循环被用来解决最大的数字是数组的第一个索引。
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);
}
}
#18
0
public class SecondHighInIntArray {
公开课SecondHighInIntArray {
public static void main(String[] args) {
int[] intArray=new int[]{2,2,1};
//{2,2,1,12,3,7,9,-1,-5,7};
int secHigh=findSecHigh(intArray);
System.out.println(secHigh);
}
private static int findSecHigh(int[] intArray) {
int highest=Integer.MIN_VALUE;
int sechighest=Integer.MIN_VALUE;
int len=intArray.length;
for(int i=0;i<len;i++)
{
if(intArray[i]>highest)
{
sechighest=highest;
highest=intArray[i];
continue;
}
if(intArray[i]<highest && intArray[i]>sechighest)
{
sechighest=intArray[i];
continue;
}
}
return sechighest;
}
}
}
#19
0
Second Largest in O(n/2)
第二大的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;
}
}
}
}
}
#20
0
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);
}
}
}
#21
0
Use following function
`
使用以下函数”
public static int secHigh(int arr[]){
int firstHigh = 0,secHigh = 0;
for(int x: arr){
if(x > firstHigh){
secHigh = firstHigh;
firstHigh = x;
}else if(x > secHigh){
secHigh = x;
}
}
return secHigh;
}
Function Call
函数调用
int secondHigh = secHigh(arr);
#22
0
import java.util.Scanner;
public class SecondLargest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter size of array : ");
int n = sc.nextInt();
int ar[] = new int[n];
for(int i=0;i<n;i++)
{
System.out.print("Enter value for array : ");
ar[i] = sc.nextInt();
}
int m=ar[0],m2=ar[0];
for(int i=0;i<n;i++)
{
if(ar[i]>m)
m=ar[i];
}
for(int i=0;i<n;i++)
{
if(ar[i]>m2 && ar[i]<m)
m2=ar[i];
}
System.out.println("Second largest : "+m2);
sc.close();
}
}
#23
0
public void findMax(int a[]) {
int large = Integer.MIN_VALUE;
int secondLarge = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
if (large < a[i]) {
secondLarge = large;
large = a[i];
} else if (a[i] > secondLarge) {
if (a[i] != large) {
secondLarge = a[i];
}
}
}
System.out.println("Large number " + large + " Second Large number " + secondLarge);
}
The above code has been tested with integer arrays having duplicate entries, negative values. Largest number and second largest number are retrived in one pass. This code only fails if array only contains multiple copy of same number like {8,8,8,8} or having only one number.
上面的代码已经用整数数组进行了测试,其中包含了重复项、负值。最大的数和第二大的数在一次传递中被检索。如果数组只包含相同数字的多个副本,如{8、8、8}或只有一个数字,则此代码只会失败。
#24
0
public class SecondLargestNumber
{
public static void main(String[] args)
{
int[] var={-11,-11,-11,-11,115,-11,-9};
int largest = 0;
int secLargest = 0;
if(var.length == 1)
{
largest = var[0];
secLargest = var[0];
}
else if(var.length > 1)
{
largest= var[0];
secLargest = var[1];
for(int i=1;i<var.length;i++)
{
if(secLargest!=largest)
{
if(var[i]>largest)
{
secLargest = largest;
largest = var[i];
}
else if(var[i]>secLargest && var[i] != largest)
{
secLargest= var[i];
}
}
else
{
if(var[i]>largest)
{
secLargest = largest;
largest = var[i];
}
else
{
secLargest = var[i];
}
}
}
}
System.out.println("Largest: "+largest+" Second Largest: "+secLargest);
}
}
#25
0
/* Function to print the second largest elements */
void print2largest(int arr[], int arr_size)
{
int i, first, second;
/* There should be atleast two elements */
if (arr_size < 2)
{
printf(" Invalid Input ");
return;
}
first = second = INT_MIN;
for (i = 0; i < arr_size ; i ++)
{
/* If current element is smaller than first
then update both first and second */
if (arr[i] > first)
{
second = first;
first = arr[i];
}
/* If arr[i] is in between first and
second then update second */
else if (arr[i] > second && arr[i] != first)
second = arr[i];
}
if (second == INT_MIN)
printf("There is no second largest elementn");
else
printf("The second largest element is %dn", second);
}
#26
0
I have got the simplest logic to find the second largest number may be, it's not. The logic find sum of two number in the array which has the highest value and then check which is greater among two simple............
我有一个最简单的逻辑来找到第二个最大的数,它不是。逻辑在数组中找到两个数字的和,它具有最高的值,然后在两个简单的运算符中检查哪个更大……
int ar[]={611,4,556,107,5,55,811};
int sum=ar[0]+ar[1];
int temp=0;
int m=ar[0];
int n=ar[1];
for(int i=0;i<ar.length;i++){
for(int j=i;j<ar.length;j++){
if(i!=j){
temp=ar[i]+ar[j];
if(temp>sum){
sum=temp;
m=ar[i];
n=ar[j];
}
temp=0;
}
}
}
if(m>n){
System.out.println(n);
}
else{
System.out.println(m);
}
#27
0
import java.util.Scanner;
进口java.util.Scanner;
public class SecondHighestFromArrayTest {
公开课SecondHighestFromArrayTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter size of Array");
int size = scan.nextInt();
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = scan.nextInt();
}
System.out.println("second highest element " + getSecondHighest(arr));
}
public static int getSecondHighest(int arr[]) {
int firstHighest = arr[0];
int secondHighest = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > firstHighest) {
secondHighest = firstHighest;
firstHighest = arr[i];
} else if (arr[i] > secondHighest) {
secondHighest = arr[i];
}
}
return secondHighest;
}
}
}
#28
0
The simplest way is -
最简单的方法是-。
public class SecondLargest {
public static void main(String[] args) {
int[] arr = { 1, 2, 5, 6, 3 };
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
for (int i = 0; i < arr.length; i++) {
// If current element is smaller than first then update both first
// and second
if (arr[i] > first) {
second = first;
first = arr[i];
}
// If arr[i] is in between first and second then update second
else if (arr[i] > second && arr[i] != first) {
second = arr[i];
}
}
}
}
#29
-1
Its very easy to get the 2nd highest element in an array. I've shows below for all your reference. Hope this will be helpful.
它很容易得到数组中的第二高元素。我已经在下面展示了你所有的参考资料。希望这对你有帮助。
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]);
}
}
Ans - The second Higest Element :8
Ans -第2个最复杂的元素:8。
#30
-1
I will propose even shorter and simplest answer to the problem and it contains 2 lines of code in the method (import java.util.Arrays
is required):
我将对这个问题提出更简短和最简单的答案,它包含了方法中的两行代码(导入java.util)。数组是必需的):
public static int secMax(int[] num){
Arrays.sort(num);
temp = num[num.length-2];
return temp;
}