如何判断2阵列共享相同的元素 [英] How to tell if 2 arrays share the same element

查看:164
本文介绍了如何判断2阵列共享相同的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是我的问题的一个简单的形式。
可以说我有2个阵列。 A = {1,2}和B = {2,4,6}。
如果A和B共享的元素,然后删除B.该元素
我知道你可以遍历和A中的每个元素比较B中的每个元素,但一定是一个更好的办法!

So this is a simpler form of my problem. Lets say I have 2 arrays. A= {1,2} and B={2,4,6}. If A and B share an element then delete that element from B. I know you can loop through and compare each element in A to each element in B, but there's got to be a better way!

推荐答案

如果您的数组进行排序(或者你可以数组排序),则可以再通过两个阵列同时工作。在两个数组的开头和下去,直到你将推进超出其各自的数组结尾的指针之一:

If your arrays are sorted (or you can sort the arrays), you can then work through both arrays simultaneously. Starting at the beginning of both arrays and going until you would advance one of the pointers beyond the end of its respective array:


  • 如果A< B,则提前一个指针

  • 如果A = B,然后在B点删除元素

  • 如果A>然后B推进的B指针

这篇关于如何判断2阵列共享相同的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆