如何求两个php 数组交集的交集??

温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
LOFTER精选
网易考拉推荐
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
阅读(4978)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
loftPermalink:'',
id:'fks_095',
blogTitle:'Java求两个数组的并集、交集、差集',
blogAbstract:'import java.util.*;public class Sets {&&& /**交集*/&&& public static Set&String& intersection(Set&String& setA, Set&String& setB) {&&&&&&& Set&String& setIntersection = new HashSet&String&();&&&&&&& String s = \"\";&&&&&&& Iterator&String& iterA = setA.iterator();&&&&&&& while (iterA.hasNext()) {',
blogTag:'',
blogUrl:'blog/static/',
isPublished:1,
istop:false,
modifyTime:3,
publishTime:1,
permalink:'blog/static/',
commentCount:0,
mainCommentCount:0,
recommendCount:0,
bsrk:-100,
publisherId:0,
recomBlogHome:false,
currentRecomBlog:false,
attachmentsFileIds:[],
groupInfo:{},
friendstatus:'none',
followstatus:'unFollow',
pubSucc:'',
visitorProvince:'',
visitorCity:'',
visitorNewUser:false,
postAddInfo:{},
mset:'000',
remindgoodnightblog:false,
isBlackVisitor:false,
isShowYodaoAd:false,
hostIntro:'',
hmcon:'0',
selfRecomBlogCount:'0',
lofter_single:''
{list a as x}
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}评论-2642&
工作多年,语言经历过C#,JAVA。但是做过的项目大多以业务系统为主,曾经做过一些基础架构的工作,但算法一直在工作中应用的比较少,导致多年之后基本都忘记完了。上一次面试过程中就有一个算法题,我能做对,但是感觉不是最优方案就放弃了。最近想想做为一个程序员,算法还是有必要再补习补习。
有两个数组,int[] arrayA=new int[]{1,3,1.....},int[] arrayB=new int[]{11,3,10.....},数组元素无序且有可能存在重复元素,请输出两个数组的交集。原题大意是这样,细节可能有出入。
面试时我的方案
不用想,采用两个for循环基本就能解决问题,但我又想不出来其它优化方法,想来想去,时间白白浪费最后居然连能做对的答案都没去写。
public void testArrayIntersectionA() {
int[] arrayA = new int[]{1, 1, 2, 3, 4, 4, 5, 1, 1};
int[] arrayB = new int[]{11, 1, 22, 3, 43, 4, 5, 11, 1, 22};
Set&Integer& intersectionSet = new HashSet();
for (int i = 0; i & arrayA. i++) {
for (int j = 0; j & arrayB. j++) {
if (arrayA[i] == arrayB[j]) {
intersectionSet.add(arrayA[i]);
当时曾经想过将数组排序然后比较,但放弃了,感觉增加了排序之后性能会不一定比上面的两层for要优化。思路如下:
排序原数组
选择数组元素小的数组去与大数组做比较
验证上面的指针比较法
比如有这样的两个数组:
具体的做法如下:
初始化两数组的指针,均从0开始
将小数组的指针做为外层循环,在大数组中以大数组指针位置开始比较
如果找到相等的,记录结果,同时将大小数组的指针向后移动
如果在大数组中找到末尾都没有找到,那么小数组的指针向后移动
当小数组的指针移动到最后一个元素后结束算法
public void testArrayIntersectionB() {
int[] arrayA = new int[]{1, 1, 2, 3, 4, 4, 5, 1, 1};
int[] arrayB = new int[]{11, 1, 22, 3, 43, 4, 5, 11, 1, 22};
Set&Integer& intersectionSet = new HashSet();
Arrays.sort(arrayA);
Arrays.sort(arrayB);
int indexArrayA = 0;
int indexArrayB = 0;
int sizeArrayA = arrayA.
int sizeArrayB = arrayB.
while (indexArrayA & sizeArrayA) {
for (int i = indexArrayB; i & sizeArrayB; i++) {
if (arrayA[indexArrayA] == arrayB[i]) {
intersectionSet.add(arrayA[indexArrayA]);
indexArrayA++;
indexArrayB++;
} else if (i == sizeArrayB - 1) {
indexArrayA++;
为了测试的准确性,可以将数组的元素增多,文中只是示意的写了几个元素,实际测试过程中可以增大元素个数。同时将方法重复执行500次或者更多来测试。得到的结论是排序之后的指针方法要快于简单的两层for,具体的数据我就不贴了,因为与数组元素的组成有一定的关系。
指针比较法的优化
上面的逻辑是,从大数组的某个位置开始比较至到数组的最后一个元素,但因为我们的数组已经经过排序,实际上我们只需要比较到第一个大于的数就可以结束比较,因为后面的元素一定比前面的元素要大。
public void testArrayIntersectionC() {
int[] arrayA = new int[]{1, 1, 2, 3, 4, 4, 5, 1, 1};
int[] arrayB = new int[]{11, 1, 22, 3, 43, 4, 5, 11, 1, 22};
Set&Integer& intersectionSet = new HashSet();
Arrays.sort(arrayA);
Arrays.sort(arrayB);
int indexArrayA = 0;
int indexArrayB = 0;
int sizeArrayA = arrayA.
int sizeArrayB = arrayB.
while (indexArrayA & sizeArrayA) {
for (int i = indexArrayB; i & sizeArrayB; i++) {
if (arrayA[indexArrayA] == arrayB[i]) {
intersectionSet.add(arrayA[indexArrayA]);
indexArrayA++;
indexArrayB++;
} else if (arrayA[indexArrayA] & arrayB[i]) {
indexArrayA++;
} else if (i == sizeArrayB - 1) {
indexArrayA++;
测试结论是此方法优化有效,特别是在特定的数据场景下。
利用java已有结构Set如何?
继承了Collection接口的,包含一个retainAll的方法,我们利用Set可以非常轻松的来完成两个数组的交集。但它只能处理对象类型的Integer,所以我们先要将int[] 转换成Integer[],然后利用addAll以及retailAll来计算数组的交集。
public void testArrayIntersectionD() {
int[] arrayA = new int[]{1, 1, 2, 3, 4, 4, 5, 1, 1};
int[] arrayB = new int[]{11, 1, 22, 3, 43, 4, 5, 11, 1, 22};
int sizeArrayA=arrayA.
int sizeArrayB=arrayB.
Integer[] arrayA2=new Integer[sizeArrayA];
Integer[] arrayB2=new Integer[sizeArrayB];
for(int i=0;i&sizeArrayA;i++){
arrayA2[i]=new Integer(arrayA[i]);
for(int i=0;i&sizeArrayB;i++){
arrayB2[i]=new Integer(arrayB[i]);
Set&Integer& intersectionSet = new HashSet&Integer&();
intersectionSet.addAll(Arrays.asList(arrayA2));
intersectionSet.retainAll(Arrays.asList(arrayB2));
同样也是执行500次,利用Set求交集的性能最好。下面是retainAll的源码:应该是利用了遍历最快的迭代器的原因,后续再找时间求证下。
public boolean retainAll(Collection&?& c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator&E& it = iterator();
while (it.hasNext()) {
if (!c.contains(it.next())) {
it.remove();
modified = true;
利用队列& (此方法有数量级的优势,比较的数组元素扩大到随机生成的10000个int)
将原数组进行排序,然后将数组加入到队列中,拿元素个数较小的做为循环条件,比较两个队列peek数值。相等则输出并出队列,否则将较小值所在的队列进行出队列操作至到某个队列为空结束循环。
public void testArrayIntersectionE(int[] arrayA,int[] arrayB) {
int sizeArrayA=arrayA.
int sizeArrayB=arrayB.
Arrays.sort(arrayA);
Arrays.sort(arrayB);
Queue&Integer& queueA=new ArrayBlockingQueue&Integer&(sizeArrayA);
Queue&Integer& queueB=new ArrayBlockingQueue&Integer&(sizeArrayB);
for(int i=0;i&sizeArrayA;i++){
queueA.add(arrayA[i]);
for(int i=0;i&sizeArrayB;i++){
queueB.add(arrayB[i]);
Set&Integer& intersectionSet = new HashSet&Integer&();
while (!queueA.isEmpty()){
Integer valueA=queueA.peek();
Integer valueB=queueB.peek();
if(null==valueA||null==valueB){
if(valueA.equals(valueB)){
intersectionSet.add(valueA);
queueA.poll();
queueB.poll();
else if(valueA&valueB){
queueB.poll();
else if(valueA&valueB){
queueA.poll();
示意过程如下:
扩展问题,如果数组不是int[],而直接是Integer[],数据结果会有变化吗?
上面有提到,当时面试时我考虑的是数组排序,经过测试int[]的排序要快于Integer[]排序,数组的复制也是一样。这在一定程序上会引起测试结果的变化。同时数组内元素的内容也会影响测试结果。
是否有更好的方案?
阅读(...) 评论()记住登录一个月发表随想还能输入:200字该用户最新代码编程随想&by by by by by by [javascript]代码库function arrayIntersection ( a, b )
var ai=0, bi=0;
var result = new Array();
while ( ai & a.length && bi & b.length )
( a[ai] & b[bi] ) { ai++; }
else if ( a[ai] & b[bi] ) { bi++; }
else /* they're equal */
result.push ( a[ai] );
console.log ( arrayIntersection ( [1,2,3],[2,3,4,5,6] ) );//[2,3]分享到:更多发表评论:评论须知:1、评论每次加2分,每天上限为30;2、请文明用语,共同创建干净的技术交流环境;3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。

我要回帖

更多关于 php 数组交集 的文章

 

随机推荐