【问题标题】:Compare NSMutableArray elements to find second largest from list比较 NSMutableArray 元素以从列表中查找第二大元素
【发布时间】:2017-01-29 13:09:39
【问题描述】:

我正在尝试查找数组中的第二大数字。为什么这段代码不起作用?

NSMutableArray *array1=[[NSMutableArray alloc]initWithObjects:@5,@25,@48,@2,@52,@53, nil];
id temp,larg2;int k=0;    

while(k<2)
{

    for(int j=0;j<5-k;j++)
    {

          if( [array1 objectAtIndex:j]>[array1 objectAtIndex:j+1])
        {
            temp=[array1 objectAtIndex:j];
            [array1 replaceObjectAtIndex:j withObject:[array1 objectAtIndex:j+1]];
            [array1 replaceObjectAtIndex:j+1 withObject:temp];
        if(k==1  && j==3). //this statement is not running??
        { larg2=temp;
            NSLog(@"The answer is %@",larg2);
        }
        }
    }
    k++;

}

   NSLog(@"The value of Second Largest Element is %@",larg2);

}

如何找到第二大元素?

【问题讨论】:

  • 找不到第二大元素????

标签: ios objective-c iphone nsarray


【解决方案1】:

如果您只需要第二大项目,则无需对数组进行排序,并且您使用的排序算法非常差(它具有 O(n^2) 性能,这意味着它会变慢项目数量的平方,因此只有几百个项目开始需要很长时间才能完成,而几千个项目似乎会挂起。)

因此,尝试调试代码没有任何意义。就像“给猪涂口红”一样。

不是对数组进行排序,而是对数组进行一次遍历。设置变量largestsecondLargest。如果当前数组条目大于最大值,则检查largest是否大于secondLargest,并替换secondLargest,然后将largest替换为新的最大值。这将为您提供 O(n) 性能(完成时间与数组中的项目数呈线性关系),这比最快的排序算法更快,而且实现起来也简单得多。

如果您不关心性能,只需使用系统排序方法,然后将排序数组中的倒数第二项。系统的排序函数经过优化,通常具有 O(n log n) 的性能,这对于排序算法来说是相当不错的。

【讨论】:

    【解决方案2】:

    如果需要排除重复项,请先创建一个 NSSet,然后对数组进行降序排序,选择第二个元素。

    NSArray  * unsortedArray = @[@22,@11,@53,@15,@7,@37,@11,@92,@84,@5];
    NSSet *numberSet = [NSSet setWithArray: unsortedArray];
    NSArray *sortedNumbers = [[numberSet allObjects] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:NO] ]];
    NSNumber *secondHighest;
    if ([sortedNumbers count] > 1){
            secondHighest = sortedNumbers[1];
        }
    NSLog(@"%ld", secondHighest);
    

    没有排序:

    NSInteger max1 = -1, max2 = -1;
    for (NSInteger i = 1; i < [unsortedArray count]; ++i) {
          if ([unsortedArray[i] integerValue] > max1) {
              max2 = max1;
              max1 = [unsortedArray[i] integerValue];
           } else if ([unsortedArray[i] integerValue] > max2 && [unsortedArra1y[i] integerValue] < max1) {
                max2 = [unsortedArray[i] integerValue];
           }
        }
    NSLog(@"%ld %ld",max1, max2);
    

    如果您有少量数组,则可以使用排序方法对数组进行排序,但是对于大量元素,随着数量的增加,性能非常差 O(n^2) 和第二种方法会花费更多时间很简单,性能 O(n)。

    【讨论】:

    • 你的答案和我的很相似。然而,像 sortUsingDescriptors 这样的系统排序方法往往比 O(n^2) 性能更好。通常他们给出 O(n log n) 的性能,O(n^2) 是最坏的情况。此外,基于描述符的方法往往比基于比较器的方法(如sortedArrayUsingComparator)慢,因为它们是为非常一般的情况排序而构建的,并使用 KVO 从数组元素中提取值。使用基于比较器的方法,您可以编写代码直接比较数组元素的值,而无需 KVO 的开销
    • 是的。你是对的sortedArrayUsingComparator' 进行 n-1 次比较,每个元素最多参与比较 log n 次。
    • @GurpreetSingh,Siddhesh 的“无排序”是最佳解决方案的工作代码。如果您想要复制/粘贴代码,请使用它。
    • 我必须提交一份作业,就像你所说的那样,昨天没有交换并通过传递更改大量数字。谢谢邓肯和@Siddesh Mhatre..!!!
    • @GurpreetSingh 哦,太好了。我们正在帮助你在学校作业中作弊!
    【解决方案3】:

    试试这个

    NSArray *arr = [[NSArray alloc]initWithObjects:@20,@12,@24, nil];
    NSSet *tempSet = [NSSet setWithArray: arr];
    NSArray *arr1 = [[tempSet allObjects] sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES] ]];
    NSLog(@"%@",[arr1 objectAtIndex:1]);
    

    【讨论】:

      猜你喜欢
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 2016-03-19
      • 1970-01-01
      • 2011-04-07
      相关资源
      最近更新 更多