-
-
Save loskael/961882d85e27060c5637b78db770a1f9 to your computer and use it in GitHub Desktop.
数组去重,并将最大值放在最前面,最小值放在最后面,要求时间复杂度为 O(n)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const stat = (data) => { | |
if (!Array.isArray(data) || data.length < 2) return data; | |
let r = [], max = 0, min = 0, m = {}, vmax = data[0], vmin = data[0]; | |
data.forEach(v => { | |
if (m[v]) return; | |
m[v] = true; | |
r.push(v); | |
if (v > vmax) { | |
vmax = v; | |
max = r.length - 1; | |
} | |
if (v < vmin) { | |
vmin = v; | |
min = r.length - 1; | |
} | |
}); | |
const swap = (m, n) => { | |
let temp = r[m]; | |
r[m] = r[n]; | |
r[n] = temp; | |
}; | |
swap(max, 0); | |
swap(min || max, r.length - 1); | |
return r; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const stat = (data) => { | |
if (!Array.isArray(data) || data.length < 2) return data; | |
let r = [], max = 0, min = 0, m = {}, vmax = data[0], vmin = data[0]; | |
data.forEach(v => { | |
if (m[v]) return; | |
m[v] = true; | |
r.push(v); | |
if (v > vmax) { | |
vmax = v; | |
max = r.length - 1; | |
} | |
if (v < vmin) { | |
vmin = v; | |
min = r.length - 1; | |
} | |
}); | |
r.splice(max, 1); | |
r.splice(min - (min > max), 1); | |
r.unshift(vmax); | |
r.push(vmin); | |
return r; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const stat = (data) => { | |
if (!Array.isArray(data) || data.length < 2) return data; | |
let r = [], m = {}, vmax = data[0], vmin = data[0]; | |
data.forEach(v => { | |
if (m[v]) return; | |
m[v] = true; | |
if (v > vmax) { | |
r.unshift(vmax = v); | |
} else if (v < vmin) { | |
r.push(vmin = v); | |
} else { | |
if (r.length) { | |
let t = r.pop(); | |
t < v ? r.push(v, t) : r.push(t, v); | |
} else { | |
r.push(v); | |
} | |
} | |
}); | |
return r; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment