小红书8.28笔试题解(java选手)
后端
代码题难度一般,都是经典题。太久没刷题了,我做的还是稍微慢了点,3道题一共写了40多分钟。
A1
//经典排序public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m=in.nextInt(); int id=in.nextInt(); long arr[]=new long[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i]+=in.nextInt(); } arr[i]= (long) (arr[i]*1e6-i-1); } Arrays.sort(arr); int ans=-1; for (int i = 0; i < n ; i++) { if((arr[i]+id)%1000000==0)ans=n-i; } System.out.println(ans); }
A2
//排序+双指针 public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long k = in.nextLong(); long arr[] = new long[n]; for (int i = 0; i < n; i++) { arr[i] = in.nextInt(); } long ans = 0; Arrays.sort(arr); int j = n - 1; for (int i = 0; i < n; i++) { while (j >= 0&&arr[i] * arr[j] >= k ) { j--; } if (i > j) { ans--; } ans += n -1- j; } System.out.println(ans); }
A3
//DFS+贪心 static int ans=0; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); ArrayList arr[]=new ArrayList[n+1]; for (int i = 0; i <=n ; i++) { arr[i]=new ArrayList(); } for (int i = 0; i < n-1; i++) { int idx=in.nextInt(); arr[i+2].add(idx); arr[idx].add(i+2); } DFS(-1,1,arr,false); System.out.println(ans); } static boolean DFS(int father,int now ,ArrayList arr[],boolean can){ boolean b=true; for (int i = 0; i < arr[now].size(); i++) { int val= (int) arr[now].get(i); if(father==val)continue; b=b&!DFS(now ,val,arr,b); } if(can&&b)ans++; return can&&b; }