The rules can be summed up as follow:
Let v
be the array
Let x
a positive number in the array
- if
x
is in v
but not -x
, keep {[x]:1}
- if
x
is in v
and -x
also, keep {[x]:2}
Let y
a negative number in the array
- if
y
is in v
and -y
also do nothing (symetry of 2.)
- if
y
is in v
but not -y
, keep {[y]:1}
Now it is pretty straightforward:
- build a set of values of
v
- check all the positive keys
- foreach one, check if there exists its opposite and apply 1. or 2.
- delete any opposite keys
- for the remaining keys (which are then negative and have no opposite) apply 3.
const v = [1,1,1,-2, 3,3,-3, 4,-4,-4]
const output = {}
const s = new Set(v)
const positives = [...new Set(v.filter(x => x>= 0))]
positives.forEach(p => {
if (s.has(-p)) {
output[p] = 2
s.delete(-p)
} else {
output[p] = 1
}
s.delete(p)
})
;[...s].forEach(negative => {
output[negative] = 1
})
console.log('output', output)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…