-
Notifications
You must be signed in to change notification settings - Fork 0
/
414. Third Maximum Number
48 lines (41 loc) · 1.27 KB
/
414. Third Maximum Number
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public int thirdMax(int[] nums) {
// sort the array using sort fuction or you can sort by using bubble sort and cycle sorting ..
bubbleSort(nums);
// and then make array of size three bcoz you know that you want to return third largest element..
int[] arr = new int[3];
int count = 1;
arr[0] = nums[nums.length - 1];
for (int i = nums.length - 2; i >= 0; i--) {
if (nums[i] < arr[count - 1]) {
arr[count] = nums[i];
count++;
}
if (count == 3) {
break;
}
}
if (count < 3) {
return arr[0];
} else {
return arr[2];
}
}
// making swap fuction for bubble sort ..
void swap (int[] arr, int first , int second){
int temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
// creating thr fuction of bubble sort ..
int[] bubbleSort (int[] arr){
for ( int i =0;i<arr.length;i++){
for (int j =1; j<arr.length-i;j++){
if (arr[j-1]> arr[j]){
swap(arr, j-1,j);
}
}
}
return arr;
}
}