code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

Secondlargestelement

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

public class SecondLargestElement {
  
  static int func(int[] nums){
    int largest = 0;
    int secondLargest = -1;
    for(int i = 0;i < nums.length; i++){
      if(nums[i] > nums[largest]){
        secondLargest = largest;
        largest = i;
      } else if (nums[i]  < nums[largest]){
        if(secondLargest == -1 || nums[i] > nums[secondLargest]){
          secondLargest = i;
        }
      }
    }
    return secondLargest;
  }
  public static void main(String[] args){
    int[] nums = {10,20,30,40};
    int result = func(nums);
    System.out.println(result);
  }
}

Created 2021-10-26T03:58:01+01:00, updated 2021-10-26T19:15:26+01:00 · History · Edit