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()); } }
时间: 2024-10-11 16:35:07