给你一个包含 1 到 n 的整数数组,但数组中从 1 到 n 的数字之一丢失了。您需要提供最佳解决方案来找到丢失的数字。数组中的数字不能重复。 例如:
int[] arr1={7,5,6,1,4,2}; Missing numner : 3 int[] arr2={5,3,1,2}; Missing numner : 4
arr[0]
package org.arpit.java2blog; /* Java program to Find Largest and Smallest Number in an Array */ public class FindLargestSmallestNumberMain { public static void main(String[] args) { //array of 10 numbers int arr[] = new int[]{12,56,76,89,100,343,21,234}; //assign first element of an array to largest and smallest int smallest = arr[0]; int largest = arr[0]; for(int i=1; i< arr.length; i++) { if(arr[i] > largest) largest = arr[i]; else if (arr[i] < smallest) smallest = arr[i]; } System.out.println("Smallest Number is : " + smallest); System.out.println("Largest Number is : " + largest); } }
当你运行上面的程序时,你会得到以下输出:
Largest Number is : 343 Smallest Number is : 12