方法一

从已知数组中随机一个数,然后加入到另一个数组中,在加入之前,先检查是否已经加入过。

这种方法有很大运气成分,且数据越大,效率越低,超过一定数目,则程序几乎无法执行,会一直卡在那里,代码:

    package com.test;  
      
    import java.util.Random;  
      
      
    public class TestArray {  
     public static int runCount =0;//用于记录方法运算次数  
       
     public int []  m1(int [] arr){  
      Random ran = new Random();  
      int length = arr.length;  
      int [] newArr = new int[length];  
      int count =0;  
      while (true) {  
       runCount ++;  
       int r = ran.nextInt(length)+1;  
       if(!exist(r, newArr)){  
        newArr [count] = r;  
        count++;  
       }  
       if(count==length){  
        break;  
       }  
      }  
      System.out.println("m1 运算次数  = "+runCount);  
      return newArr;  
     }  
       
     public static boolean exist(int a,int [] arr){  
      for (int i = 0; i < arr.length; i++) {  
       if(arr[i] ==a){  
        return true;  
       }  
      }  
      return false;  
     }  
View Code

相关文章:

  • 2022-03-03
  • 2021-12-20
  • 2021-12-19
  • 2021-10-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-04
  • 2021-05-19
  • 2022-03-07
  • 2021-07-08
  • 2021-06-13
相关资源
相似解决方案