From 1e5c7fd1312a434d58c490799d30fbfdb02179fa Mon Sep 17 00:00:00 2001 From: VishwajeetK Date: Tue, 19 Nov 2024 11:28:08 +0530 Subject: [PATCH] feat: Solve leetcode problem for sorting. Level easy --- .../dsa/leet_code/easy/sorting/ThirdMax.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 JavaDsaWithTest/src/main/java/org/practice/dsa/leet_code/easy/sorting/ThirdMax.java diff --git a/JavaDsaWithTest/src/main/java/org/practice/dsa/leet_code/easy/sorting/ThirdMax.java b/JavaDsaWithTest/src/main/java/org/practice/dsa/leet_code/easy/sorting/ThirdMax.java new file mode 100644 index 0000000..ee21529 --- /dev/null +++ b/JavaDsaWithTest/src/main/java/org/practice/dsa/leet_code/easy/sorting/ThirdMax.java @@ -0,0 +1,43 @@ +package org.practice.dsa.leet_code.easy.sorting; + +public class ThirdMax { + public static void main(String[] args) { + int[] arr = {2,1,3}; + System.out.println(thirdMax(arr));; + } + + public static int thirdMax(int[] nums) { + + sort(nums); + int pointer =0; + for (int i = nums.length-1; i >=0 ; i--) { + if (i == nums.length-1 || nums[i] !=nums[i+1]) { + pointer++; + } + + if (pointer == 3) { + return nums[i]; + } + } + return nums[nums.length -1]; + } + + private static void sort(int[] nums) { + boolean isSwap; + + for (int i = 0; i < nums.length-1; i++) { + isSwap = false; + for (int j = 1; j < nums.length -1- i; j++) { + if (nums[j] < nums[j-1]) { + int temp = nums[j]; + nums[j] = nums[j-1]; + nums[j-1] = temp; + isSwap = true; + } + } + if (!isSwap) { + break; + } + } + } +}