ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

洛谷题--三位数排序

洛谷题--三位数排序 题目描述给出三个整数 a,b,c(0≤a,b,c≤100)要求把这三位整数从小到大排序。输入格式输入三个整数 a,b,c以空格隔开。输出格式输出一行三个整数表示从小到大排序后的结果。初始版本import java.util.Scanner; public class Main{ public static void main(String[] arg){ Scanner sc new Scanner(System.in); int a sc.nextInt(); int b sc.nextInt(); int c sc.nextInt(); if(ab){ if(bc){ System.out.println(a b c); }else{ if(ac){ System.out.println(a c b); }else{ System.out.println(c a b); } } }else{ if(bc){ System.out.println(c b a); }else{ if(ac){ System.out.println(b c a); }else{ System.out.println(b a c); } } } } }存在问题虽然逻辑正确但代码繁琐可读性差优化方案方案一依然只用if,简化版本不再写多层嵌套用临时变量交换保证 a ≤ b ≤ c代码短、逻辑直白import java.util.Scanner; public class Main{ public static void main(String[] arg){ Scanner sc new Scanner(System.in); int a sc.nextInt(); int b sc.nextInt(); int c sc.nextInt(); int t; // 如果a比b大交换a,b if (a b) { t a; a b; b t; } // 如果a比c大交换a,c → a一定是最小值 if (a c) { t a; a c; c t; } // 最后保证b ≤ c if (b c) { t b; b c; c t; } System.out.println(a b c); } }✅ 优点没有地狱式嵌套 if阅读轻松改动一个数字也不容易出错完全只用 if 判断符合分支结构作业要求方案二数组 工具类排序刷题、竞赛最优解把 3 个数放进数组调用 Java自带排序函数(局限是只能从小到大排序代码最少import java.util.Scanner; import java.util.Arrays; public class Main{ public static void main(String[] arg){ Scanner sc new Scanner(System.in); int[] nums {sc.nextInt(), sc.nextInt(), sc.nextInt()}; Arrays.sort(nums); System.out.println(nums[0] nums[1] nums[2]); } }✅ 优点以后如果不是 3 个数是 100 个数几乎不用改代码逻辑干净不会写错判断分支方案三Math.max/ Math.min 纯计算版趣味写法不用交换变量直接算出最小、中间、最大值import java.util.Scanner; public class Main{ public static void main(String[] arg){ Scanner sc new Scanner(System.in); int a sc.nextInt(); int b sc.nextInt(); int c sc.nextInt(); int min Math.min(Math.min(a,b),c); int max Math.max(Math.max(a,b),c); int mid a b c - min - max; System.out.println(min mid max); } }原理三个数总和减去最大值、最小值剩下的就是中间值非常巧妙
返回列表