输入 n 个数字,不使用排序,找出最大的三个数。
利用一次for循环解决
public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入数组长度:"); int length = sc.nextInt();//数组长度 System.out.println("请输入数组:"); int[] arr = new int[length]; for (int i = 0; i < arr.length; i++) { arr[i] = sc.nextInt(); } int max1 =0; int max2 =0; int max3 =0; for (int i = 0; i < arr.length; i++){ int current = arr[i]; if (max1 < current){ max3 = max2; max2 = max1; max1 = current; } else if(max2 < current){ max3 = max2; max2 = current; }else if (max3 < current){ max3 = current; } } System.out.println(max1); System.out.println(max2); System.out.println(max3); }
结果:
可以自己多测试两组
只是简单基础的题目,有瑕疵,主要目的还是如何解决问题(解决问题方法很多,在此不一一列举)