检测数组中唯一值的数量 [英] Detect the number of unique values in an array

查看:85
本文介绍了检测数组中唯一值的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种检测数组中唯一值数量的有效方法。

I am looking for an efficient way to detect the number of unique values in an array.

我当前的方法:


  1. 快速排序整数数组

  2. 然后运行循环以比较元素。

在代码中:

  yearHolder := '';
  for I := 0 to  High(yearArray) do
  begin
    currYear := yearArray[i];
    if (yearHolder <> currYear) then
    begin
      yearHolder := currYear;
      Inc(uniqueYearNumber);
    end;
  end;


推荐答案

下面是THashedStringList的示例:

Here is an example with the THashedStringList:

hl := THashedStringList.Create; // in Inifiles
try
  hl.Sorted := True;
  hl.Duplicates := dupIgnore; // ignores attempts to add duplicates
  for i := 0 to  High(yearArray) do
    hl.Add(yearArray[i]);
  uniqueYearCount := hl.Count;
finally
  hl.Free;
end;

这篇关于检测数组中唯一值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆