-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharraySecondMax.js
More file actions
83 lines (66 loc) · 1.82 KB
/
arraySecondMax.js
File metadata and controls
83 lines (66 loc) · 1.82 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
'use strict';
// Method one ------------------------------------------------------
/**
* Returns the second largest value in an array
* If array is empty or has less than 2 values, returns null;
* @param {Array} arr
* @returns {Number|null} second largest value in array
*/
function findSecondMax1(arr) {
if (arr.length <= 1) return null;
let max1 = arr[0];
let max2 = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max1) {
max2 = max1;
max1 = arr[i];
} else if (arr[i] > max2) {
max2 = arr[i];
}
}
return max2;
}
// Method two ------------------------------------------------------
/**
* Returns the second largest value in an array
* If array is empty or has less than 2 values, returns null;
* @param {Array} arr
* @returns {Number|null} second largest value in array
*/
function findSecondMax2(arr) {
if (arr.length <= 1) return null;
let maxIdx = findMax(arr).idx;
arr.splice(maxIdx, 1);
return findMax(arr).max;
}
/**
* Returns the max value in an array and it's idx
*
* @param {Array} arr
* @returns {Object} { idx, max }
*/
function findMax(arr) {
let idx = 0;
let max = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] > max) {
idx = i;
max = arr[i];
}
}
return {idx, max};
}
// Method three ----------------------------------------------------
/**
* Returns the second largest value in an array
* If array is empty or has less than 2 values, returns null;
* @param {Array} arr
* @returns {Number|null} second largest value in array
*/
function findSecondMax3(arr) {
if (arr.length <= 1) return null;
arr.sort((a,b) => a - b); // O(n^2)
return arr[arr.length - 2];
}
// -----------------------------------------------------------------
module.exports = [findSecondMax1, findSecondMax2, findSecondMax3];