如何解决在给定数组中查找最小值和最大值,其中约束的最小值索引应小于其最大值
给定数组 ["1510","1518","1520","1523","1530","1483","1485"] 预期输出:-
Smallest - 1510
Largest - 1530
另一个数组 ["310","314","320","319","323","313","330"] 预期输出:-
Smallest - 310
Largest - 330
我下面的代码获取最小值和最大值,它在解决上面列出的第一个问题时遇到问题,因为它返回 1483 作为最小和 1485 作为最大。 max 和 min 之间的差异应该更大。
知道如何获得吗?
function minMax(array) {
if(array.length <= 0) return [0,0];
let max = Math.max.apply(null,array);
let min = Math.min.apply(null,array);
let max_index = array.lastIndexOf(String(max));
let min_index = array.indexOf(String(min));
if(min_index >= max_index) {
array.splice(max_index,1);
[min,max] = minMax(array);
}
return [min,max];
}
解决方法
单次遍历数组:
- 从数组的末尾迭代到开头。
- 跟踪最大值和最小值以及最小值/最大值对的列表
- 检查每一项
- 如果找到的项目超过当前的最大值,
- 将当前最小值/最大值添加到对列表中
- 将当前项目设为最大值并重置最小值
- 否则,如果当前项小于当前最小值,则将其设为最小值。
- 否则什么都不做。
- 如果找到的项目超过当前的最大值,
- 然后将最后一个最小/最大对添加到列表中。
此时,您有一个要返回的潜在最小/最大对的列表。您必须从头到尾检查它们,以找到设置了最小值的第一个并将其返回。或者返回一组默认的最小值/最大值。
function minMax(arr) {
let max = -Infinity;
let min = Infinity;
const candidates = [];
for (let i = arr.length-1; i >= 0; i--) {
const item = Number(arr[i]);
if (item > max) {
candidates.push([min,max]);
max = item;
min = Infinity;
} else if (item < min) {
min = item;
}
}
candidates.push([min,max]);
// Instead of return fixed first or last element below code would return first element from last which is finite.
for(let i = candidates.length - 1; i >= 0; i--) {
if(Number.isFinite(candidates[i][0])) return candidates[i];
}
return [0,0];
}
console.log(minMax(["1510","1518","1520","1523","1530","1483","1485"]));
console.log(minMax(["310","314","320","319","323","313","330"]));
console.log(minMax(["350","330"]));
console.log(minMax(["7","6","1","2"]));
console.log(minMax(["4","3","2","1"]));
你可以使用类似下面的东西
function minMax(array) {
let max = Math.max.apply(null,array)
let newArray= array.slice(0,array.indexOf(+max)-1)
let min=Math.min.apply(null,newArray);
return [min,max];
}
,
你可以
- 取一组局部最小值和最大值,
- 将它们分组为最小和最大对,如果两个值都存在,
- 如果在更大的索引上找到最大值,则更改最大值,
- 获取增量最大的一对。
function minMax(numbers) {
return numbers
.reduce((r,v,i,a) => {
if (!(r.length & 1) === a[i - 1] < v) r[r.length - 1] = v;
else r.push(v);
return r;
},[])
.reduce((r,a) => {
if (i & 1) r.push([a[i - 1],v]);
return r;
},[min,max],a) => (r || a).map(([left,right],j) => [
left,i > j && max > right ? max : right
]),undefined)
.reduce((a,b) => a[1] - a[0] >= b[1] - b[0] ? a : b);
}
console.log(minMax([1510,1518,1520,1523,1530,1483,1485])); // 1510 1530
console.log(minMax([310,314,320,319,323,313,330])); // 310 330
console.log(minMax([9,3,4,1])); // 3 4
.as-console-wrapper { max-height: 100% !important; top: 0; }
这个问题和buy and sell stock一样。您首先需要购买股票并尽可能多地出售。因此,在每个索引处,您需要知道右侧的最大元素。
- 从末尾遍历数组,并在每个索引处存储到目前为止的最大元素。
For the list [1510,1485] maxList will look like [1530,1485,1485] difference [20,12,10,7,2,0 ] so answer will be 1510 and 1530.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。