RT.个人项目上的一个问题,写了个例子,自己感觉写的方法较笨。😅
https://www.wolai.com/beCZEzzoibLdm9yfrNrDCo
ps:不过挺享受洗澡时在想代码怎么写,洗完立即把想到的写法敲出来😂
|  |      1javapythongo      2021-04-09 00:18:17 +08:00 你这个算法的时间复杂度是 O(m*n)了,而且在 if(x[i] == y[j])判定相等赋值后,应该直接 break 。 可以先遍历 y 数组,存储在一个 set 集合中,再遍历 x 数组,原地修改即可,这样子的时间复杂度是 O(m+n) | 
|  |      2LGA1150      2021-04-09 00:19:24 +08:00 int[] x = {1,2,3,4,5,6,7}; int[] y = {2,4,7}; int[] z = Arrays.stream(x).map(e -> Arrays.binarySearch(y, e) < 0 ? 0 : e).toArray(); System.out.println(Arrays.toString(z)); 需要保证 y 有序 | 
|  |      3LGA1150      2021-04-09 00:28:24 +08:00 如果像 #1 说的使用集合并原地修改: Set<Integer> set = Arrays.stream(y).boxed().collect(Collectors.toSet()); for (int i = 0; i < x.length; i++) { if (!set.contains(x[i])) x[i]=0; } 不用保证 y 有序 | 
|  |      4zjp      2021-04-09 00:35:38 +08:00 不假设数组有序和不重复的情况 int[] x = {1, 2, 3, 4, 5, 6, 7}; int[] y = {2, 4, 7}; Map<Integer, Long> count = Arrays.stream(y).boxed() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); int[] z = Arrays.stream(x).boxed() .map(e -> count.containsKey(e) && count.put(e, count.get(e) - 1) > 0 ? e : 0) .mapToInt(Integer::intValue).toArray(); System.out.println("z = " + Arrays.toString(z)); | 
|  |      6LowBi OP | 
|  |      7no1xsyzy      2021-04-09 09:26:43 +08:00 | 
|      8youhuo      2021-04-09 13:51:02 +08:00 来学习 学习 |