贝壳:举重大赛(暴力计数)
1. 题目
代码
方法1 AC 45%
import java.util.Scanner; public class Main { private static int N;//正整数个数 public static void main(String[] args) { Scanner sc = new Scanner(System.in); N = sc.nextInt(); sc.nextLine(); int [] val = new int[N];//正整数 String[] str = sc.nextLine().split(" "); for (int i = 0; i < N; i++) { val[i] = Integer.valueOf(str[i]); } int max = 0; for (int i = 0; i < N; i++) { for (int j = i+1; j < N; j++) { if(val[i]==val[j] || (val[i]>val[j] && val[j]>= val[i]*0.9) || (val[i] < val[j] && val[i]>= val[j]*0.9)){ max++; continue; } } } System.out.println(max); } }
方法二,先排序,再比较
import java.util.Arrays; import java.util.Scanner; public class A1 { private static int N;//正整数个数 public static void main(String[] args) { Scanner sc = new Scanner(System.in); N = sc.nextInt(); sc.nextLine(); int [] val = new int[N];//正整数 String[] str = sc.nextLine().split(" "); for (int i = 0; i < N; i++) { val[i] = Integer.valueOf(str[i]); } int max = count(N,val); System.out.println(max); } public static int count(int n, int[] nums) { if(nums == null || nums.length == 0) return 0; Arrays.sort(nums); int count = 0; for(int i = 0; i < n-1; i++) { for(int j = i+1; j < n; j++) { if(nums[j] <= (nums[i]*10/9)){ count++; } else { break; } } } return count; } }