给定2个未排序的数组和一个和,给出两个数字,当加上它们时,等于总和

时间:2017-04-20 01:52:08

标签: algorithm array-algorithms

在这些数组中,数字可以是正数也可以是负数。 每个阵列只能使用一个数字。

我在电话采访中收到了这个问题作为算法问题,这让我很难过。面试官似乎相信有一个O(n)解决方案。

编辑:我的问题与“可能的重复”不同,因为这个问题涉及2个数组,而不是一个。

1 个答案:

答案 0 :(得分:6)

对于未排序的数组 - 使用第一个数组值填充哈希表并遍历第二个数组值,检查表中是否存在var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope, filterFilter, $timeout) { Array.prototype.sum = function(prop) { var ptotal = 0 for (var i = 0, _len = this.length; i < _len; i++) { ptotal += this[i][prop] } return ptotal } $scope.owners = [{ "id": "1", "name": "parent 1" }, { "id": "2", "name": "parent 2" }, { "id": "3", "name": "parent 3" }]; $scope.children = [{ "id": "1", "total": "2", "owner": "1", "name": "child 1" }, { "id": "2", "total": "2", "owner": "2", "name": "child 2" }, { "id": "3", "total": "1", "owner": "2", "name": "child 3" }, { "id": "4", "total": "5", "owner": "3", "name": "child 4" }, { "id": "5", "total": "2", "owner": "1", "name": "child 5" }]; // var uTotal = $scope.children.sum("total"); var random = Math.floor(Math.random() * $scope.owners.length); $scope.selectedOwner = $scope.owners[random]; $scope.childrenList = $scope.children.filter(function(x) { return x.owner == $scope.selectedOwner.id; }); $scope.ownerChange = function(owner) { $scope.selectedOwner = owner; $scope.childrenList = $scope.children.filter(function(x) { return x.owner == $scope.selectedOwner.id; }); } $scope.data = []; $scope.remove = function(child) { for (var i3 = $scope.data.length - 1; i3 >= 0; i3--) { if ($scope.data[i3].number == child.number && $scope.data[i3].id == child.id) { $scope.data.splice(i3, 1); } } } $scope.add = function(child) { $scope.totalInit = filterFilter($scope.children, { owner: child.owner }); var total = $scope.totalInit.sum("total"); var complete = filterFilter($scope.data, { id: +child.id }).length; var number = +complete + 1; var input = { "id": child.id, "name": child.name, "number": number }; if (+number == +child.total) { $scope.data.push(input); for (var i = $scope.children.length - 1; i >= 0; i--) { if ($scope.children[i].id == child.id) { $scope.children.splice(i, 1); } } $scope.childrenList = $scope.children.filter(function(x) { return x.owner == $scope.selectedOwner.id; }); $scope.ownerStatus = filterFilter($scope.children, { owner: child.owner }).length; if ($scope.ownerStatus === 0) { for (var i2 = $scope.owners.length - 1; i2 >= 0; i2--) { if ($scope.owners[i2].id == child.owner) { $scope.owners.splice(i2, 1); } } var random2 = Math.floor(Math.random() * $scope.owners.length); $scope.selectedOwner = $scope.owners[random2]; $scope.childrenList = $scope.children.filter(function(x) { return x.owner == $scope.selectedOwner.id; }); if ($scope.owners.length === 0) { alert("All Trials Complete"); $scope.children = []; $scope.owners = []; } } } else { $scope.data.push(input); } }; });