java - 我想使用递归检查一个整数在数组中是否唯一
问题描述
//删除方法
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;
}
}
}
我如何检查唯一性?
解决方案
这永远不会为您提供您正在寻找的 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");
}}
推荐阅读
- git - 文件名中的“+”字符导致 git blame 失败
- php - 发送多个数组以在 codeigniter 中查看
- c# - (Visual Studio 2015 - 2017)不创建文件夹(目录),也不在 Properties.settings 中保存任何值
- algorithm - 最长递增子序列的长度,O(n) 复杂度
- css - Visual Studio Code 无法识别 CSS 文件中的变量
- python - 捕获丢失文件的 Tkinter 异常
- android - 从未显示在 ImageView 中的图库或相机照片中选择
- python - 多列上的 Pandas get_dummies
- gams-math - 随机生成100个数据,或者选择是否可以
- java - Recursive minimal tree creating function buggy?