使用递归方式打印数组
class Solution{
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5};
printArr(arr);
}
private static void printArr(int[] arr) {
printArr(arr, 0);
}
private static void printArr(int[] arr, int i) {
if (i == arr.length) {
return;
}
System.out.println(arr[i]);
printArr(arr, i + 1);
}
}
for循环找数
class Solution {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5};
int target = 3;
saerch(arr, target);
}
private static int saerch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
}
class Solution {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5};
int target = 3;
int res = search(arr, target);
System.out.println(res);
}
private static int search(int[] arr, int target) {
return search(arr, 0, target);
}
private static int search(int[] arr, int i, int target) {
if (i > arr.length) {
return -1;
}
if (arr[i] == target) {
return i;
}
return search(arr, i + 1, target);
}
}
倒序打印
class Solution{
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5};
printArr(arr);
}
private static void printArr(int[] arr) {
printArr(arr, 0);
}
private static void printArr(int[] arr, int i) {
if (i == arr.length) {
return;
}
printArr(arr, i + 1);
System.out.println(arr[i]);
}
}