讨论 "据说是微软的考题(出自<<世界500强试题>>)"
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.