【问题标题】:Pick Out Specific Number from Array? [duplicate]从数组中挑选出特定的数字? [复制]
【发布时间】:2012-06-24 12:52:36
【问题描述】:

我有一堆充满数字的 NSArray。无论如何,我可以以某种方式获取一个特定的数字,特别是:

数组中第三大的数字,还是数组中的第 24 大数字?

但我不想只获取数字,我还需要对它在数组中的索引的引用,如果可以在过程中保留的话。

谢谢。

【问题讨论】:

    标签: iphone objective-c ipad nsarray


    【解决方案1】:

    数组中第三大的数字,还是数组中的第 24 大数字?

    创建数组的临时副本并按升序对其进行排序。
    获取索引3-1 或24-1 处的数字。

    我还需要引用它在数组中的索引

    现在使用indexOfObject: 或indexOfObjectIdenticalTo: 来获取实际索引。

    【讨论】:

      【解决方案2】:

      从我的答案Getting Top 10 Highest Numbers From Array? 中的排序numbers 数组开始:

      NSUInteger wanted = 24 or anything;
      
      NSUInteger count = 0;
      NSNumber* previous = nil;
      for (NSDictionary* entry in numbers)
      {
          if ( wanted == 1 ) return entry;
      
          if (previous == nil)
          {
              // first entry
              previous = entry[@"number"];
              ++ count;
      
              continue;
          }
      
          // same number? skip it.
          if ( entry[@"number"] isEqualTo: previous ) continue;
      
          // if we get here, we found a different number we may be interested in
      
          ++ count;
      
          if ( count == wanted ) return entry;
      }
      
      // nothing found
      return nil;
      

      结果是上一个问题的numbers 数组中的一行。 @[ @"number" : @<number>, @"parent" : <source array> ] 形式的数组。

      【讨论】:

      • 顺便说一句,您可以调整该代码以查找字典中前 10 个唯一的最高数字。使用相等测试(带有否定)来增加计数而不是跳过,并将条目添加到数组中直到 count == 10 而不是返回条目。很简单。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多