假设我有一个只包含数字和特殊字符E
的数组。该数组可以包含多个E
。只要遇到E,我的函数应该返回当前整个集合中的最小数字。
function OffLineMinimum(strArr) {
var arr = [],
len = strArr.length,
res = [],
i = 0;
while (i < len) {
if (strArr[i] != "E") {
arr.push(parseInt(strArr[i]));
i++;
} else {
res.push(arr.sort(function(a, b) {
return a - b;
})[0]);
i = i + 2;
}
}
return res.join(",");
}
console.log(OffLineMinimum(["5", "4", "6", "E", "1", "7", "E", "E", "3", "2"]));
// output: 4,1,5
答案 0 :(得分:1)
方法首先获取数组中%include "io.mac"
.STACK 100H
.DATA
Numbers DW 3,4,5,2,6,0
msg0 db "Printing values in array",0
msg1 db "Max",0
.CODE
.STARTUP
PutStr msg0
mov dx, Numbers
mov si, dx ;point to array
printValues:
cmp word [si], 0
je procedure
nwln
PutInt [si]
add si, 2
jmp printValues
procedure:
push Numbers ;push Number to stack to pass parameter by stack
call maxMeth
nwln
PutStr msg1
nwln
PutInt ax
nwln
PutInt bx
nwln
complete:
.EXIT
maxMeth:
enter 0,0 ;save old bp and set bp to sp
mov si, [bp+4] ;point to array
mov ax, [si] ; ax holds max
mov bx, [si] ; ax holds max
add si,2 ; Increment si to next number
;Now entering loop
max:
cmp word [si],0 ; checks to see if the number is 0 and if it is, then we are done.
je finish ;equals 0, then finished
cmp ax, [si]
jg testSecondMax ;So if ax is greater than si, then dont assign si to ax and check second max
jmp newMax ;otherwise go to new max
newMax:
mov ax, [si] ; save new max
jmp increment ; and increment
testSecondMax:
cmp bx, [si]
jl secondMax
jg increment
secondMax:
mov bx, [si]
jmp increment
increment:
add si, 2 ;now increment si to check the next value and jump back to the main loop.
jmp max
finish: ;clean up.
leave ;pop bp
ret ;return
的所有索引然后遍历该数组切片并将主数组过滤到该索引,然后得到该子集的min
"E"
答案 1 :(得分:0)
根据问题,这似乎是你想要的
var t1 = ["5", "4", "6", "E", "1", "7", "E", "E", "3", "2"];
var t2 = ["5", "4", "6", "E", "8", "7", "E", "E", "3", "2"];
function OffLineMinimum(strArr) {
return strArr.reduce((result, item) => {
if (item === 'E') {
result.output.push(result.work.sort((a, b) => a - b).shift());
} else {
result.work.push(Number(item));
}
return result;
}, {output: [], work: []}).output;
}
console.log(OffLineMinimum(t1).toString());
console.log(OffLineMinimum(t2).toString());
然而,t2,根据评论应该导致4,7,5
所以逻辑完全没有描述。但似乎连续的第二个E
使用到目前为止的剩余完整集,其中第一个应该使用自上一个E
以来的当前“块”
代码:
var t1 = ["5", "4", "6", "E", "1", "7", "E", "E", "3", "2"];
var t2 = ["5", "4", "6", "E", "8", "7", "E", "E", "3", "2"];
function OffLineMinimum(strArr) {
return strArr.reduce((result, item) => {
if (item === 'E') {
if (result.lastItem === 'E') {
result.output.push(result.work.sort((a, b) => a - b).shift());
} else {
result.output.push(result.block.sort((a, b) => a - b).shift());
result.work.push(...result.block);
result.block = [];
}
} else {
result.block.push(Number(item));
}
result.lastItem = item;
return result;
}, {output: [], work: [], block: [], lastItem: ''}).output;
}
console.log(OffLineMinimum(t1).toString())
console.log(OffLineMinimum(t2).toString())