今日头条编程题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了今日头条编程题相关的知识,希望对你有一定的参考价值。
1.两数组找相同的元素-array
50%
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); int m = cin.nextInt(); int[] a = new int[m]; for (int i = 0; i < m; i++) { a[i] = cin.nextInt(); } int n = cin.nextInt(); int[] b = new int[n]; for (int i = 0; i < n; i++) { b[i] = cin.nextInt(); } helper(a, b); } public static void helper(int[] a, int[] b) { int m = a.length; int n = b.length; for (int j = 0; j < n; j++) { for (int i = 0; i < m; i++) { if (a[i] == b[j]) System.out.println(b[j]); } } } }
50% TLE/OLE
import java.util.Scanner; import java.util.Set; import java.util.HashSet; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); int m = cin.nextInt(); int[] a = new int[m]; for (int i = 0; i < m; i++) { a[i] = cin.nextInt(); } int n = cin.nextInt(); int[] b = new int[n]; for (int i = 0; i < n; i++) { b[i] = cin.nextInt(); } //将a中的数据添加到Hashset中,利用hashset的不重复性来比较b数组中的数据; Set<Integer> set = new HashSet<Integer>(); String rst = ""; for (int i = 0; i < m; i++) { set.add(a[i]); } for (int j = 0; j < n; j++) { if (!set.add(b[j])) { rst += b[j] + " "; } } System.out.println(rst.trim()); } }
以上是关于今日头条编程题的主要内容,如果未能解决你的问题,请参考以下文章