Java 查找数组中第二大的数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2615712/
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
Finding the second highest number in array
提问by Richard Hymanson
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_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];
回答by Nathan S.
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.
如果 second_highest 最初设置的第一个元素已经是最高元素,那么在找到下一个元素时应该将其重新分配给新元素。也就是说,它被初始化为 98,应该设置为 56。但是,56 不高于 98,所以它不会被设置,除非你做检查。
If the highest number appears twice, this will result in the second highest valueas opposed to the second elementthat you would find if you sorted the array.
如果最高数字出现两次,这将导致第二个最高值,而不是您在对数组进行排序时会找到的第二个元素。
回答by Scott Smith
// 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:
编辑:
哎呀。谢谢你指出我的错误,伙计们。现在固定。回答by polygenelubricants
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)
,但实际上,Integer.MIN_VALUE
如果数组中没有至少 2 个元素,它将返回。Integer.MIN_VALUE
如果数组只包含相同的数字,它也会返回。
回答by Chander Shivdasani
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;
}
回答by csaam
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.
这会将重复项视为相同的数字。如果您希望所有最大的和第二大的都重复,您可以更改条件检查。
回答by Stranger
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.
如果时间复杂度不是问题,那么您可以运行冒泡排序,并且在两次迭代中,您将获得第二大数字,因为在循环的第一次迭代中,最大的数字将移至最后一个。在第二次迭代中,倒数第二大的数字将被移动到最后。
回答by Harsh Kevadia
If you want to 2nd highest and highest number index in array then....
如果你想在数组中获得第二高和最高的数字索引,那么......
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");
}
}
回答by Ash_P
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 - 第二大元素:8
回答by Prashant Jain
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);
}
回答by Georgi Koemdzhiev
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):
我将针对该问题提出更短和最简单的答案,它在方法中包含 2 行代码(import java.util.Arrays
必需):
public static int secMax(int[] num){
Arrays.sort(num);
temp = num[num.length-2];
return temp;
}