给出一个包含重复项的整数数组,返回一个数组,其中所有对索引的总和为零。
[1, 2, 3, -1, 5, -5, 7, 9, -7, 2, -2] -> [ [ 3, 0 ], [ 5, 4 ], [ 8, 6 ], [ 10, 1 ], [ 10, 9 ] ]
我的JS解决方案:
function pairs(values, i) {
if (values) {
values.push(i);
return values;
}
return [i];
}
function twoSum(arr) {
const results = [];
const map = new Map();
arr.forEach((ele, i) => {
if (map.get(-ele)) {
map.get(-ele).forEach((e) => results.push([i, e]));
}
map.set(ele, pairs(map.get(ele), i));
});
return results;
}
来自Ruby,这是我的Ruby解决方案:
def two_sum(arr)
hash = Hash.new { |h, k| h[k] = [] }
arr.each.with_index.each_with_object([]) do |(ele, i), results|
if hash.key?(-ele)
hash[-ele].each { |e| results << [i, e] }
end
hash[ele] << i
end
end
这个想法是每个哈希图键都有一个数组,对于数组中的每个元素,我们检查哈希图是否具有-element键,如果是,则将当前索引对和每个值对推入结果数组
如何使JS解决方案更加惯用?我在JS默认库(与Ruby相比)中找不到以下内容:
稍微重构了选定的解决方案,并得出以下结论:
function twoSum(arr) {
const hash = new Map();
return arr.reduce((results, ele, i) => {
if (hash.has(-ele)) hash.get(-ele).forEach((e) => results.push([i, e]));
hash.get(ele) ? hash.get(ele).push(i) : hash.set(ele, [i]);
return results;
}, []);
}
答案 0 :(得分:2)
POST
答案 1 :(得分:0)
也许是这样的
function Get-GroupMembers {
$prompt = "Enter A Group Name. Press Q to quit"
# create an endless loop
while ($true) {
Clear-Host
$answer = Read-Host $prompt
# if the user has had enough, exit the function
if ($answer -eq 'Q') { return }
# try and find one or more AD groups using the answer as (part of) the name
$group = Get-ADGroup -Filter "Name -like '*$answer*'"
# if we have found something, exit the while loop and start enumerating the members
if ($group) { break }
$prompt = "Group '$answer' was not found, try again. Press Q to quit"
}
# you only get here if Get-ADGroup found one or more groups
$group | ForEach-Object {
# output a PSObject with the properties you are after
$members = $_ | Get-ADGroupMember
foreach ($member in $members) {
[PsCustomObject]@{
'Group' = $_.DistinguishedName
'Member' = $member.DistinguishedName
}
}
}
}
# call the function
$groupinfo = Get-GroupMembers
# test if the function returned anything.
# the user could have cancelled of the group had no members to output
if ($groupinfo) {
Write-Host "Adding $($groupinfo.Count) items to the CSV file"
# without -Append, you would overwrite your CSV file..
$groupinfo | Export-Csv .\GroupMembers.csv -NoTypeInformation -Append
}
else {
Write-Host 'Nothing found..'
}