![](/img/trans.png)
[英]Efficient algorithm to compute combinations with repetitions of an array adding up to given sum
[英]High efficient algorithm for picking up number from array
这是问题所在:
一个数组中有2 * N + 1个整数,并且有N个对整数,即两个1或两个3等,所以只有一个整数,没有对。
问题是如何使用高效算法找到该数字。
感谢您提供任何线索或意见。
好的,好的,这是我评论的解释。 :-/
missingNum = 0
for each value in list
missingNum = missingNum ^ value //^ = xor
next
print(missingNum)
这是一个线性算法,O(n)。
那么这是怎么回事? 说,对于熟悉XOR运算符的人,我们有[2,1,3,1,2]
,知道1 ^ 1 = 0
0 ^ 0 = 0
和1 ^ 0 = 1
0 ^ 1 = 1
(记住没有携带)
因此从本质上讲,当我们对一个比特序列(100110111)进行XOR运算时,它的偶数为1
,每个数将对XOR自身进行零运算……如果1's
数量为奇数,则XOR得出1
因此,在我们的示例中,从lsb开始
2 : 0010
1 : 0001
3 : 0011
1 : 0001
2 : 0010
lsb bit: 0 ^ 1 ^ 1 ^ 1 ^ 0 : 1
2nd bit: 1 ^ 0 ^ 1 ^ 0 ^ 1 : 1
3rd bit: 0 ^ 0 ^ 0 ^ 0 ^ 0 : 0
4th bit: 0 ^ 0 ^ 0 ^ 0 ^ 0 : 0
所以我们缺少的号码是
0011 = 3
您可以在此问题中找到更通用的答案。 如果假设n=2, m=1
您将得到想要的。
但是,正如st0le所说,在您的情况下,XOR就足够了。
如果我正确地理解了这个问题,那么您将得到一个包含奇数个整数值的数组,该数组由多个出现两次的整数加上一个仅出现一次的整数组成。 例如,数组可能如下所示:
[3, 41, 6, 6, 41]
其中6和41都是重复的,而3是唯一的。
最好知道是否还有其他限制。 例如:
[1, 2, 2, 2, 1]
是有效输入,是一对1,一对2和一个未配对的2? 假设数组未排序,这是一个以伪代码表示的解决方案,它以O(N)时间运行,并且最多需要原始数组的大约一半的存储空间。
SEEN = []
for N in ARRAY:
if N in SEEN:
remove N from SEEN
else:
add N to SEEN
if size of SEEN != 1:
error - ARRAY doesn't contain exactly 1 un-paired value
else:
answer = SEEN[0]
这是一个使用NSMutableDictionary存储可见值的示例实现,假定源数组是纯C数组。
#import <Foundation/Foundation.h>
int main(int argc, char argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int array[9] = {3, 4, 5, 6, 7, 6, 5, 4, 3};
NSMutableDictionary *d = [NSMutableDictionary dictionaryWithCapacity:16];
for (int i = 0; i < sizeof(array)/sizeof(int); i++) {
NSNumber *num = [NSNumber numberWithInt:array[i]];
if ([d objectForKey:num]) {
[d removeObjectForKey:num];
} else {
[d setObject:[NSNull null] forKey:num];
}
}
if ([d count] == 1) {
NSLog(@"Unpaired number: %i", [[[d keyEnumerator] nextObject] intValue]);
} else {
NSLog(@"Error: Expected 1 unpaired number, found %u", [d count]);
}
[pool release];
return 1;
}
它正在运行:
$ gcc -lobjc -framework Foundation -std=c99 demo.m ; ./a.out
2010-12-25 11:23:21.426 a.out[17544:903] Unpaired number: 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.