【发布时间】:2011-02-04 07:03:42
【问题描述】:
我看到一个面试问题如下: 给出一个由整数 A 和一个整数 I 组成的未排序数组,找出 A 的任何两个成员加起来是否为 I。
有什么线索吗?
时间复杂度应该更低
【问题讨论】:
标签: algorithm
我看到一个面试问题如下: 给出一个由整数 A 和一个整数 I 组成的未排序数组,找出 A 的任何两个成员加起来是否为 I。
有什么线索吗?
时间复杂度应该更低
【问题讨论】:
标签: algorithm
将元素插入哈希表。
在插入x 时,检查I-x 是否已经存在。 O(n) 预计时间。
否则,对数组进行升序排序(从索引 0 到 n-1)。有两个指针,一个在最大值,一个在最小值(分别称为 M 和 m)。
If a[M] + a[m] > I then M--
If a[M] + a[m] < I then m++
If a[M] + a[m] == I you have found it
If m > M, no such numbers exist.
【讨论】:
如果您有整数所在的范围,则可以使用类似计数排序的解决方案,在该解决方案中扫描数组并对数组进行计数。例如你有整数
input = [0,1,5,2,6,4,2]
然后你创建一个这样的数组:
count = int[7]
其中(在 Java、C# 等中)适合计算 0 到 6 之间的整数。
foreach integer in input
count[i] = count[i] + 1
这将为您提供数组[1,1,2,0,1,1,1]。现在你可以扫描这个数组(它的一半)并检查是否有整数加起来等于i 像
for j = 0 to count.length - 1
if count[j] != 0 and count[i - j] != 0 then // Check for array out-of-bounds here
WUHUU! the integers j and i - j adds up
总体而言,该算法为您提供O(n + k),其中 n 来自对长度为 n 的输入的扫描,k 是对长度为 k 的计数数组的扫描(0 和 k - 1 之间的整数)。这意味着如果 n > k 则您有一个有保证的 O(n) 解决方案。
【讨论】:
input = [0, 250, 500, 750, 1000] 这样的边缘情况,您需要一个巨大的数组来存储计数。我宁愿使用哈希表。
例如,循环并添加可能的数字来设置或散列,如果找到,则返回它。
>>> A = [11,3,2,9,12,15]
>>> I = 14
>>> S = set()
>>> for x in A:
... if x in S:
... print I-x, x
... S.add(I-x)
...
11 3
2 12
>>>
【讨论】:
A 中的每个元素X,对I-X 执行二分搜索。如果I-X 在A 中,我们有一个解决方案。这是O(nlogn)。
如果A 包含给定(足够小)范围内的整数,我们可以使用技巧使其成为O(n):
V。对于A 中的每个元素X,我们递增V[X]。V[X] 时,我们还会检查V[I-X] 是否为>0。如果是,我们有一个解决方案。【讨论】:
I-1 的项目以加快搜索速度,尽管最坏情况下的性能是相同的。
public static boolean findSum2(int[] a, int sum) {
if (a.length == 0) {
return false;
}
Arrays.sort(a);
int i = 0;
int j = a.length - 1;
while (i < j) {
int tmp = a[i] + a[j];
if (tmp == sum) {
System.out.println(a[i] + "+" + a[j] + "=" + sum);
return true;
} else if (tmp > sum) {
j--;
} else {
i++;
}
}
return false;
}
【讨论】:
O(n) time and O(1) space
如果数组已排序,则有一个 O(n) 时间复杂度的解。
假设数组是
array = {0, 1, 3, 5, 8, 10, 14}
还有我们的x1 + x2 = k = 13,所以输出应该是= 5, 8
array[ptr1] + array[ptr2]
if sum > k then decrement ptr2 else increment ptr1
这里详细解释了同样的事情。好像是亚马逊面试问题 http://inder-gnu.blogspot.com/2007/10/find-two-nos-in-array-whose-sum-x.html
【讨论】:
for nlogn :对数组进行排序,对于每个元素 [0<=j<len A] ,减去 i-A[j] 并在排序后的数组中对该元素进行二分搜索。
hashmap (frequency of no, number) 应该在 O(n) 中工作。
【讨论】:
for each ele in the array
if (sum - ele) is hashed and hashed value is not equal to index of ele
print ele, sum-ele
end-if
Hash ele as key and index as value
end-for
【讨论】:
PERL 实现,用于检测排序数组是否包含两个总和为 Number 的整数
my @a = (11,3,2,9,12,15);
my @b = sort {$a <=> $b} @a;
my %hash;
my $sum = 14;
my $index = 0;
foreach my $ele (@b) {
my $sum_minus_ele = $sum - $ele;
print "Trace: $ele :: $index :: $sum_minus_ele\n";
if(exists($hash{$sum_minus_ele}) && $hash{$sum_minus_ele} != $index ) {
print "\tElement: ".$ele." :: Sum-ele: ".$sum_minus_ele."\n";
}
$hash{$ele} = $index;
$index++;
}
【讨论】:
这可能通过以下方式实现:在将元素放入 hashmap 之前,您可以检查元素是否大于所需的总和。如果是,您可以简单地跳过该元素,否则您可以继续将其放入哈希图中。尽管总体时间仍然保持不变,但它对您的算法略有改进。
【讨论】:
这可以使用 UNION-FIND 算法来解决,该算法可以在恒定时间内检查一个元素是否在一个集合中。
所以,算法是这样的:
foundsum0 = false;
foreach (el: array) {
if find (-x): foundsum0 = true;
else union (x);
}
FIND 和 UNION 是常数,O(1)。
【讨论】:
这是一个使用 O(n) 额外空间的 java 中的 O(n) 解决方案。这里使用hashSet来实现
【讨论】:
这是一个考虑重复条目的解决方案。它是用 javascript 编写的,并假定数组已排序。该解决方案在 O(n) 时间内运行,并且除了变量之外不使用任何额外的内存。选择选择的排序算法。 (基数 O(kn)!),然后通过这个婴儿运行数组。
var count_pairs = function(_arr,x) {
if(!x) x = 0;
var pairs = 0;
var i = 0;
var k = _arr.length-1;
if((k+1)<2) return pairs;
var halfX = x/2;
while(i<k) {
var curK = _arr[k];
var curI = _arr[i];
var pairsThisLoop = 0;
if(curK+curI==x) {
// if midpoint and equal find combinations
if(curK==curI) {
var comb = 1;
while(--k>=i) pairs+=(comb++);
break;
}
// count pair and k duplicates
pairsThisLoop++;
while(_arr[--k]==curK) pairsThisLoop++;
// add k side pairs to running total for every i side pair found
pairs+=pairsThisLoop;
while(_arr[++i]==curI) pairs+=pairsThisLoop;
} else {
// if we are at a mid point
if(curK==curI) break;
var distK = Math.abs(halfX-curK);
var distI = Math.abs(halfX-curI);
if(distI > distK) while(_arr[++i]==curI);
else while(_arr[--k]==curK);
}
}
return pairs;
}
我在一家大公司的面试中解决了这个问题。他们拿走了,但我没有。 所以这里适合所有人。
从数组的两侧开始,慢慢地向内工作,确保计算重复项(如果存在)。
它只计算对,但可以重做
尽情享受吧,如果它是最好的解决方案,别忘了碰碰!
【讨论】:
将数组分成两组 I/2。然后将它们分成 I/4 和 3I/4 并重复 log(I) 步骤并检查从外部连接的对,例如 1I/87I/8,如果它们都包含至少一个元素,则它们添加到 I。 这将需要 n.Log(I) + n/2 步骤,对于 I
【讨论】:
python 中的实现
def func(list,k):
temp={} ## temporary dictionary
for i in range(len(list)):
if(list[i] in temp): ## if temp already has the key just increment its value
temp[list[i]] +=1
else: ## else initialize the key in temp with count as 0
temp[list[i]]=0
if(k-list[i] in temp and ((k/2 != list[i]) or temp[list[i]]>=1)): ## if the corresponding other value to make the sum k is in the dictionary and its either not k/2 or the count for that number is more than 1
return True
return False
输入:
list 是数字列表(上述问题中的 A)...
k 是总和(我在上面的问题中)....
如果列表中有一对总和等于k,则函数输出True,否则输出False...
我正在使用一个字典,其键是数组(列表)中的元素,值是该元素的计数(该元素在该列表中出现的次数)。 平均运行时间复杂度为 O(n)。
这个实现还处理了两个重要的边缘情况:
【讨论】: