算出两个集合的补集
算出两个数组的补集,数组只包含字符串和数字
说明:补集:如果 b 是 a 的⼦集,返回存在于 a 不存在于 b 的元素集合,反之返回空集合
思路
因为数组只包含字符串和数字,所以不用考虑对象、数组的情况。分别求相对于另一个数组的补。如果两个补集的相加的长度等于两个数组相加的长度,说明都没有交集,根据题目描述直接返回空集合,反之则返回两个补集的组合就是这两个数组的补集。
function findComplementarySet(a, b) {
let res = [...a.filter(x => !b.includes(x)), ...b.filter(x => !a.includes(x))]
if (res.length === a.length + b.length) {
return []
} else {
return res.sort()
}
}
计算出⼀个数组内的所有波峰和波⾕,并返回它们的坐标。
说明:计算出⼀个数组内的所有波峰和波⾕
- 数组内的每个元素均不相等
- 波峰:⽐邻近的左、右元素都要⼤
- 波⾕:⽐邻近的左、右元素都要小
function findTurns (arr) {
let tops = []
let lows = []
let topsIndex = []
let lowsIndex = []
for(let i = 0; i < arr.length; i++) {
if (i === 0) {
if (arr[0] < arr[1]) {
lows.push(arr[0])
lowsIndex.push(0)
} else {
tops.push(arr[0])
topsIndex.push(0)
}
} else if (i === arr.length - 1) {
if (arr[i] < arr[i-1]) {
lows.push(arr[i])
lowsIndex.push(i)
} else {
tops.push(arr[i])
topsIndex.push(i)
}
} else {
if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {
tops.push(arr[i])
topsIndex.push(i)
}
if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) {
lows.push(arr[i])
lowsIndex.push(i)
}
}
})
return {
tops,
lows,
topsIndex,
lowsIndex
}
}