[英]Check whether there is a path in an array whose sum is sum by recursion in java
[英]I want to check whether an integer is unique inside an array using recursion
//移除方法
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");
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.