一个包含99个元素的数组,存储了1-100中的99个数字,除了1个以外,这99个数字是乱序排列的。现让你找出到底缺的是哪个数字,要求:1)只能遍历一次;2)除了数组本身以外,只有2个整数单元的额外存储空间。 import java.util. * ; import java.io. * ; public class Some ... { public static final int HOWMANY=10; public static boolean whetherStep; //生成这样一个序列(a[1]到a[9]存放的是1~10少掉一个数,a[0]不使用,a[10]用掉一个空间),并给出少掉的那个数 public static int fill(int[]kaka)...{ ArrayList al=new ArrayList(); for(int i=1;i<=HOWMANY;i++)...{ al.add(new Integer(i)); } //生成无序的数组 for(int i=1;i<=HOWMANY-1;i++)...{ int pos=(int)(Math.random()*al.size()); kaka[i]=((Integer)al.get(pos)).intValue(); al.remove(pos); } kaka[HOWMANY]=-1; return ((Integer)al.get(0)).intValue(); } //本算法的核心部分,swap用掉一个空间 public static int swap(int[]a,int i,int index)...{ //交换a[i]和a[a[i]]; int space2=a[i]; a[i]=a[space2]; a[space2]=space2; if(a[i]==-1)...{ return i; }else...{ return index; } } //为了能看清楚其执行的步骤,按一下回车,就输出一次现在的数组的情况。 public static void pr(int[]a)...{ try...{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); br.readLine(); printArray(a); }catch(Exception e)...{} } //寻找, public static int find(int[]a)...{ int space1=HOWMANY; int i=1; while(i<=HOWMANY)...{ if(whetherStep)...{ pr(a); } if (a[i] != i&&space1!=i) ...{ //这样交换意思是为了把i这个数放到a[i]这个位置上去 //最后找出来时,应该是数组中i全都放到a[i]中,跟踪那个空位(即存放-1的地方),就是要找的数 space1=swap(a,i,space1); } else ...{ i++; } } return space1; } //打印出数组 public static void printArray(int[]a)...{ for(int i=1;i<a.length;i++)...{ System.out.print(a[i]+" "); } System.out.println(); } public static void main(String[]args)...{ int []h=new int[HOWMANY+1]; int left=fill(h); System.out.println("the lost one is "+left); printArray(h); System.out.println(" ********************************"); System.out.println("缺一个数的数组已经给出,现在选择要不要看分步执行情况[y/n]"); try...{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String ans=br.readLine(); if(ans.trim().equals("y")||ans.trim().equals("Y"))...{ whetherStep=true; }else...{ whetherStep=false; } }catch(Exception e)...{} System.out.println("now ,find the lost number,it's "+find(h)); }}