0902饿了么笔试AK代码
Q1
package ali.eleme; import java.util.Arrays; import java.util.Scanner; public class P1 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = scan.nextInt(); Arrays.sort(array); int l = 0, r = n - 1; long ans = 0; while (r - l >= 2) { ans += array[l++] + array[r--]; r--; } for (int i = l; i <= r; i++) ans += array[i]; System.out.println(ans); } }
Q2
package ali.eleme; import java.util.Scanner; public class P2 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); while (t-- > 0) { String s = scan.next(), tar = scan.next(); int n = tar.length(), zeroTar = 0, zeroS = 0; for (int i = 0; i < n; i++) { if (tar.charAt(i) == '0') zeroTar++; if (s.charAt(i) == '0') zeroS++; } if (zeroS == n && zeroTar != n) System.out.println("NO"); else if (zeroS != n && zeroTar == n) System.out.println("NO"); else System.out.println("YES"); } } }
Q3
package ali.eleme; import java.util.Scanner; public class P3 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(), k = scan.nextInt(); int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = scan.nextInt(); SegmentTree segmentTree = new SegmentTree(array); int ans = n, l = 0, r = 0; long sum = 0; while (r < n) { sum += array[r]; while (sum >= k) { ans = Math.min(ans, r - l + 1); if (sum - segmentTree.query(1, 0, n - 1, l, r) >= k) { ans = Math.min(ans, r - l); } sum -= array[l++]; } r++; } System.out.println(ans); } static class SegmentTree { int[] tree, array; public SegmentTree(int[] array) { this.array = array; this.tree = new int[4 * array.length]; build(1, 0, array.length - 1); } private void build(int node, int s, int e) { if (s == e) tree[node] = array[s]; else { int mid = s + e >> 1; build(node << 1, s, mid); build(node << 1 | 1, mid + 1, e); tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]); } } public int query(int node, int s, int e, int l, int r) { if (s > r || e < l) return Integer.MAX_VALUE; if (s >= l && e <= r) return tree[node]; int mid = s + e >> 1; int leftMin = query(node << 1, s, mid, l, r); int rightMin = query(node << 1 | 1, mid + 1, e, l, r); return Math.min(leftMin, rightMin); } } }#阿里##饿了么##饿了么笔试#