讨论 "据说是微软的考题(出自<<世界500强试题>>)"

pankun 2005-03-31 02:11:56
http://community.csdn.net/Expert/TopicView3.asp?id=3893746
白天听SeaWave老大说了这个贴子,觉的有点意思,晚上无意想起了一个不用辅助存储和循环变量的办法,但这种方法只能找到重复的数的一个位置,大家讨论一下还有不有什么好的办法能找到二个位置,最好栈都不用.

我的算法如下:
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;

type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

const
//只测试11个
test: array [0..10] of Integer = (2, 7, 4, 5, 1, 3, 8, 9, 5, 10, 6);

implementation

{$R *.dfm}
function find(index: Integer): boolean;
begin
if test[index] < 0 then
begin
result := true;
exit;
end;
test[index] := 0 - test[index];
if find(0 - test[index] - 1) then
//输出数及位置
ShowMessage(IntToStr(0 - test[index]) + ' at:' + IntToStr(index + 1));
//恢复数据
test[index] := 0 - test[index];
result := false;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
find(10)
end;

end.
...全文
145 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
sunware 2005-03-31
  • 打赏
  • 举报
回复
昨天仔细一想,其实求和的做法是不妥当的。

因为从题目的条件来看,程序的运行环境应是内存极度匮乏,在这种情况下,整形应判断为短整形(signed 16-bit或unsigned 16-bit)。这样,求和结果为500500,超过了短整形的上限了。所以求和是求不出来的。
sunware 2005-03-31
  • 打赏
  • 举报
回复
昨天仔细一想,其实求和的做法是不妥当的。

因为从题目的条件来看,程序的运行环境应是内存极度匮乏,在这种情况下,整形应判断为短整形(signed 16-bit或unsigned 16-bit)。这样,求和结果为500500,超过了短整形的上限了。所以求和是求不出来的。
pankun 2005-03-31
  • 打赏
  • 举报
回复
没人有兴趣吗?算了结帐
nadel 2005-03-31
  • 打赏
  • 举报
回复
漏了:for i:= 0 to 10 do
nadel 2005-03-31
  • 打赏
  • 举报
回复
把test转成double再求和。
nadel 2005-03-31
  • 打赏
  • 举报
回复
uses
Math;

...

for 0 to 10 do
if test[i] = Sum(test) - 55 then
showmessage(inttostr(test[i]) + '重复,位置为:' + inttostr(i));
何鲁青 2005-03-31
  • 打赏
  • 举报
回复
关注...学习ing
hc0007 2005-03-31
  • 打赏
  • 举报
回复
相加再减去 (1+2+..+1000) 不是更快吗
pankun 2005-03-31
  • 打赏
  • 举报
回复
更改一下
procedure TForm1.FormCreate(Sender: TObject);
begin
find(High(test))
end;

16,748

社区成员

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

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