关于计算重复数据次数的算法问题,请各位指教

pxsisan 2020-01-29 07:02:05

面对以上stringgrid里的文字(这表格不连数据库的),想统计出来重复字的数量(结果 冯:3,徐:2) 个数为1的不显示统计,怎么写代码?
...全文
269 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
pxsisan 2020-02-03
  • 打赏
  • 举报
回复
这个问题已经解决了,我用以下方法解决的。
var
tempList,strList,cemplist:TStringList;
i,s,m,n,t,c1,k1:Integer;
begin
edit5.Text:='';
s:=0;
strList:= TStringList.Create; cemplist:= TStringList.Create; tempList:= TStringList.Create;
try
for c1:=0 to stringgrid2.RowCount-1 do
strList.Add(stringgrid2.Cells[1,c1+1]);

for i:=1 to strList.Count-1 do
begin
if tempList.IndexOf( strList.Strings[i])=-1 then
begin
tempList.Add( strList.Strings[ i ] );
end
end;
for s:=0 to templist.Count-1 do
begin
m:=0;
for k1:=0 to strlist.Count-1 do
begin
if templist.Strings[s]=strlist.Strings[k1] then
begin
m:=m+1
end;
end;
cemplist.Add(inttostr(m));
end;
for t:=0 to cemplist.Count-1 do
if cempList.strings[t]='1' then
begin
cemplist.Delete(t);
templist.Delete(t);
cemplist.Insert(t,'');
templist.Insert(t,'');
end;
for i:=0 to tempList.Count-1 do
if cempList.strings[i]<>'' then
begin
edit5.Text:= edit5.Text+tempList[ i ]+cempList[i]+'次';
end;

finally
tempList.Free;
strList.Free;
cemplist.Free;
end;
end;
pxsisan 2020-02-03
  • 打赏
  • 举报
回复
语句精炼,值得学习!
  • 打赏
  • 举报
回复

uses System.SysUtils, System.Generics.Collections;

procedure StatGrid(const Grid: TStringGrid);
var
D: TDictionary<string, integer>;
S: string;
P: TPair<string, integer>;
i: integer;
begin
D := TDictionary<string, integer>.Create;
for i := Grid.FixedRows to Grid.RowCount - 1 do
begin
S := Grid.Cells[Grid.FixedCols, i];
if D.ContainsKey(S) then D[S] := D[S] + 1 else D.Add(S, 1);
end;

for P in D do
if P.Value = 1 then
writeln(P.Key) // 怎样显示或存储看你的需要
else
writeln(Format('%s:%d', [P.Key, P.Value])); // 怎样显示或存储看你的需要
D.Free;
end;


使用:StatGrid(StringGrid1);
pxsisan 2020-02-03
  • 打赏
  • 举报
回复
引用 4 楼 早打大打打核战争 的回复:
还可以,就是实现比较繁琐,用泛型TDictionary<string, integer>可以很简单解决

不会用啊,请指教!
  • 打赏
  • 举报
回复
还可以,就是实现比较繁琐,用泛型TDictionary<string, integer>可以很简单解决
半道道 2020-02-01
  • 打赏
  • 举报
回复
遍历整个字符串,利用HashMap建立字典,时间复杂度O(N) + O(LogN) ,但是数据量大的话,内存可能撑不住。 之前遇到一面试题:字符串文本大小为1TB,如何统计数据次数? 利用分治策略,将数据切割到有限小,分不到不同计算机上进行处理,最后合并统计,利用MapReduce也可以统计。
  • 打赏
  • 举报
回复
如果用数据库的话很容易:select xxx, count(xxx) from tablename group by xxx;
但是你没用到数据库,可以用TDictionary<string, integer>建立字典统计一下

16,748

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 语言基础/算法/系统设计
社区管理员
  • 语言基础/算法/系统设计社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧