首页 > 解决方案 > 我想使用递归检查一个整数在数组中是否唯一

问题描述

//删除方法

public static int[] remove(int[]a){
int [] x = new int[a.length - 1];

for(int i = 1; i <= x.length; i++) {
    x[i-1] = a[i];  
}

return x;}

IsUniqueMethod 检查 Passed int 的唯一性

public static boolean isUnique(int []x, int n) {
if(x.length == 1) { 
    return true;}
else {
    
    if(x[0] != n) {
        return isUnique(remove(x), n);
    }
    else {
    return false;
    }
    
}

}

我如何检查唯一性?

标签: javarecursion

解决方案


这永远不会为您提供您正在寻找的 isUnique() 输出。即使您以某种方式通过了 ArrayIndexOutOfBound,您编写的代码也非常低效,以至于每次您在递归调用中传递方法参数时都会调用 JIT。

试试这个

import java.util.ArrayList;
import java.util.Scanner;

public class Unique {

     private static Scanner sc;

     public static void main(String[] args) {

         sc = new Scanner(System.in);

         //Taking length of the array from the user
         System.out.println("Enter the length of the desired array : ");
         int length = sc.nextInt();

         System.out.println("Please enter the values of the array");
         ArrayList<Integer> al = new ArrayList<Integer>();

         //Entering the values into the arrayList
         for (int i = 0; i < length; i++) {
             al.add(sc.nextInt());
         }

         System.out.println("Enter a number you wish to check : ");
         int checkNumber = sc.nextInt();

         //Using the built-in method indexOf() to check the occurance of the entered number and return its index if present, else returns -1
         System.out.println(al.indexOf(checkNumber)>=0?"The entered number is present in the array":"The entered number is not present in the array");

     }}

推荐阅读