1

我如何查看我的整数是否在整数数组中......

例如,我想知道 7 是否在 [ 1 3 4 5 6 7 8] 的数组中

有任何想法吗?

谢谢

4

3 回答 3

6

有几种方法可以做到这一点,具体取决于数组大小等因素 - 您需要搜索的频率,需要添加到数组的频率等。通常这是一个计算机科学问题。

更具体地说,我猜有三个选项可能最适合您的需求。

  1. “蛮力”:只需循环遍历数组以查找值。调用containsObject:NSArray为你做这件事。对于小数组大小来说简单且可能最快。
  2. 将数组复制到一个集合中并用于containsObject:检查是否存在
  3. 将值保留在数组中,但对数组进行排序并实现您自己的二进制搜索——这可能不像听起来那么复杂。
于 2010-04-12T08:10:58.147 回答
3

这取决于您拥有的数组类型,是对象还是 C 数组。从你的标签来看,你有一个带有 NSIntegers 的 NSArray,这是错误的。NSInteger 不是对象,不能放入 NSArray,除非将它们包装到对象中,例如 NSNumber。

NSArray

使用containsObject:方法。

我不完全确定您如何将整数放入 NSArray。通常的方法是使用 NSNumber。

NSArray *theArray = [NSArray arrayWithObjects:[NSNumber numberWithInteger:1],
                                              [NSNumber numberWithInteger:7],
                                              [NSNumber numberWithInteger:3],
                                              nil];
NSNumber *theNumber = [NSNumber numberWithInteger:12];
/*
 * if you've got the plain NSInteger you can wrap it
 * into an object like this:
 * NSInteger theInt = 12;
 * NSNumber *theNumber = [NSNumber numberWithInteger:theInt];
 */
if ([theArray containsObject:theNumber]) {
    // do something
}

C阵列

我怀疑您使用的是C-Array。在这种情况下,您必须编写自己的循环。

NSInteger theArray[3] = {1,7,3}
NSInteger theNumber = 12;
for (int i; i < 3; i++) {
    if (theArray[i] == theNumber) {
        // do something
        break; // don't do it twice
               // if the number is twice in it
    }
}
于 2010-04-12T08:10:18.010 回答
0
//assume these data, either from a method call or instance variables
int theArray[7] = {1,7,3,8,5,7,4};
int numberIWant = 8;

//this is the essence in a C-array, which you can easily use on ios
BOOL isNumberFound = NO;
for (int i; i < sizeof(theArray)/sizeof(int); i++) {
    if (theArray[i] == numberIWant) {
        isNumberFound = YES;
        break; //breaks the for loop               
    }
}
//return the bool, or otherwise check the bool

if (isNumberFound)
{
//do stuff
}
于 2011-01-04T20:41:05.463 回答