查找数组中第二高的数字

我很难理解该方法背后的逻辑,以查找数组中第二高的数字。 使用的方法是find数组中最高的,但比先前的最高(已经find)。 我仍然无法弄清楚的原因是|| highest_score == second_highest || highest_score == second_highest是必要的。 例如我input三个数字: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]; 

我不相信做你所做的修复了这个问题。 我认为它掩盖了你的逻辑中的另一个问题。 find第二高实际上是相当简单的:

  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; } 

这是一个O(N) 。 如果你想接受关系,那么改为if (num >= high1) ,但是如果数组中至less有2个元素,它将返回Integer.MIN_VALUE 。 如果数组只包含相同的数字,它也会返回Integer.MIN_VALUE

 // 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 

编辑:

哎呦。 谢谢你指出我的错误,伙计们。 现在修好了

如果second_highest的第一个元素最初被设置为最高元素,那么当find下一个元素时,它应该被重新分配给一个新的元素。 也就是说,它被初始化为98,应该设置为56.但是,56不会高于98,所以除非你做检查,否则不会被设置。

如果最高数字出现两次,这将导致第二高的 ,而不是第二个元素 ,如果你sorting数组,你会发现。

  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; } 
 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 

如果时间复杂性不是问题,那么你可以运行冒泡sorting,在两次迭代中,你将得到第二高的数字,因为在循环的第一次迭代中,最大的数字将被移动到最后一个。 在第二次迭代中,第二大数字将被移到最后。

如果你想在数组中的第二高和最高的数字指数,然后….

 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"); } } 
 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(); } } } 

你可以find最大和第三大的未sorting数组。

  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); } } 

我看到的答案不会工作,如果有两个相同的最大数字,如下面的例子。

  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()); 

我已经从Set而不是从数组中移除它

我提供的解决scheme不在JAVA程序(用JavaScript编写)中,但是需要o(n / 2)次迭代才能find最高和次高的数字。
工作小提琴手链接提琴手链接

  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]; } } } 
 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 

如果这个问题是来自面试官,那么请不要使用SORTING技术或不要使用像Arrays.sort或Collection.sort这样的内置方法。 这个问题的目的是解决你的解决scheme在性能方面是多么的优秀,所以最好的select就是用你自己的逻辑来实现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); } 

问题:问题是获得第二大数组元素。

观察:第二大数字被定义为从数组中最大元素减去时具有最小差异的数字。

解决scheme:这是一个双通解决scheme。 第一遍是find最大数量。 第二遍是find与其他数组元素相比最小元素差异最小的元素。 例如:在数组[2,3,6,6,5]最大值= 6,第二最大值= 5,因为它与最大元素6 – 5 = 1的最小差异,第二大= 5

 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); } 

复杂性:O(n),这是最简单的方法。

为了更有效地find最大元素,可以查看最大堆 ,调用max-heapify将花费O(log n)时间来查找最大值,然后popup顶部元素给出最大值。 为了获得第二个最大值,在popup顶部并保持popup状态,直到您得到一个小于最大值的数字为止,max-heapify。 那将是第二个最大值。 该解决scheme具有O(n log n)复杂性。

 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); } 

这将重复处理为相同的数字。 你可以改变条件检查,如果你想所有的最大和第二大重复。

请尝试这一个:使用这种方法,你可以罚款第二大数组中偶数组包含随机数。 第一个循环是用来解决这个问题,如果最大的数字是第一个索引的数组。

 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); } } 

公共类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; } 

}

第二大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; } } } } } 
 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); } } } 

使用以下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; } 

函数调用

 int secondHigh = secHigh(arr); 
 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(); } } 
 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); } 

上面的代码已经用具有重复条目的负数值的整数数组进行了testing。 一次回合中数量最多,次数最多。 如果数组只包含像{8,8,8,8}这样的相同数字的多个副本或只有一个数字,则此代码仅失败。

 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); } } 
  /* 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); } 

我有最简单的逻辑来find第二大的数字,可能不是。 逻辑find数组中两个数的和,然后在两个简单的数组中检查哪一个数更大…………

 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); } 

import java.util.Scanner;

公共类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; } 

}

它很容易获得数组中的第二高元素。 我已经在下面显示了所有的参考。 希望这会有所帮助。

 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 – 第二个最高元素:8

我认为find第二个最高不,我们需要这些线,如果我们可以使用内置function

 int[] randomIntegers = {1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9}; Arrays.sort(randomIntegers); System.out.println(randomIntegers[randomIntegers.length-2]); 
 static int secondLargest(int[] input){ int largest , secondlargest; if(input[0]>input[1]) { largest=input[0]; secondlargest = input[1]; } else { secondlargest = input[0]; largest =input[1]; } for(int i =2 ;i<input.length;i++){ if(input[i]>largest) { secondlargest = largest; largest = input[i]; } else if(input[i]>secondlargest){ secondlargest = input[i]; } } return secondlargest; } 

find第二大数字:

 public class SecondMaxNumbers { public void printTwoMaxNumbers(int[] nums){ int maxOne = 0; int maxTwo = 0; for(int n:nums){ if(maxOne < n){ maxTwo = maxOne; maxOne =n; } else if(maxTwo < n){ maxTwo = n; } } System.out.println("Second Max Number: "+maxTwo); } public static void main(String a[]){ int num[] = {10,20,30,40,50,60,70}; SecondMaxNumbers sec = new SecondMaxNumbers(); tmn.printTwoMaxNumbers(num); } }