java實現:2018年9月9日晚上的京東筆試題:現給出n個物品的a,b,c引數,請你求出不合格品的數量。
阿新 • • 發佈:2018-11-16
題目:
現有n個物品,每個物品有三個引數,ai,bi,ci,定義i物品不合格的依據是:若存在物品j,且aj>ai,bj>bi,cj>ci,則稱i物品為不合格品。
現給出n個物品的a,b,c引數,請你求出不合格品的數量。
輸入:
第一行包含一個整數n(1<=n<=500000),表示物品的數量,接下來有n行,每行三個整數,ai,bi,ci表示第i個物品的三個引數,1<=ai,bi,ci<=10^9.
輸出:
輸出包含一個整數,表示不合格品的數量
樣例輸入:
3
1 4 2
4 3 2
2 5 3
樣例輸出:
1
說明:第二行和第四行比較:1<2; 4<5; 2<3,所以第一行是不合格品。
其餘不滿足,所以不合格品是1
思路:
就是把第i個產品和其他所有產品比較,如果a,b,c都比另一產品j對應的a,b,c小,說明i是不合格的。
所以我們可以把第i個產品和其餘的對比,只要存在第j個產品滿足:ai<aj; bi<bj; ci<cj; 就把不合格品數量num++,然後break
方法一:
package test20190907; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int num = 0; int[][] things = new int[n][3]; while (sc.hasNext()) { int arr[] = new int[n * n]; for (int i = 0; i < n; i++) { for (int j = 0; j < 3; j++) { things[i][j] = sc.nextInt(); } } } // for (int i = 0; i < n * n; i++) { // System.out.println(arr[i]); // } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (things[i][0] < things[j][0] && things[i][1] < things[j][1] && things[i][2] < things[j][2]) { num++; break; } } } System.out.println(num); } }
控制檯:
方法二:
package test20190907; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { int n = sc.nextInt(); int num = 0; int arr[] = new int[3 * n]; for (int i = 0; i < 3 * n; i++) { arr[i] = sc.nextInt(); } // for (int i = 0; i < 3 * n; i++) { // System.out.println(arr[i]); // } for (int i = 0, j = i + 1, k = j + 1; k < 3 * n ; i = i + 3, j = j + 3, k = k + 3) { for (int a = 0, b = a + 1, c = b + 1; c < 3 * n; a = a + 3, b = b + 3, c = c + 3) { if (arr[i] < arr[a] && arr[j] < arr[b] && arr[k] < arr[c]) { num++; break; // System.out.println("a的值是" + a + "i的值是" + i); } } } System.out.println(num); } } }
控制檯:
上邊方法一是通過所有案例
方法二沒有在牛客網上跑過,其實核心原理都是和我寫的思路一樣。