本文介绍了拆分数组唯一对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我先从一个简单的数组(可以是任何长度的理论上):
$ IDS =阵列(1,2,3,4);什么是分裂这个数组唯一对像数组中选择最佳的解决方案:
$一双[0] =阵列(1,2);$对[1] =阵列(1,3);$对[2] =阵列(1,4);$对[3] =阵列(2,3);$对[4] =阵列(2,4);$对[5] =阵列(3,4);解决方案
最简单的解决方法是使用嵌套循环和构建组合,当您去,但请注意,这里复杂度为O(N 2 )。
$ IDS =阵列(1,2,3,4,4);$组合=阵列();$ IDS = array_unique($ IDS); //删除重复$ num_ids =计数($ IDS);为($ I = 0; $ I< $ num_ids; $ I ++){ 为($ J = $ I + 1; $ J< $ num_ids; $ J ++) { $组合[] =阵列($ IDS [$ i],$ IDS [$ J]); }}在操作中查看在 www.ideone/9wzvP
Say i start with a simple array (which could be theoretically of any length):
$ids = array(1,2,3,4);What it the best solution for splitting this array into an array of unique pairs like:
$pair[0] = array(1,2); $pair[1] = array(1,3); $pair[2] = array(1,4); $pair[3] = array(2,3); $pair[4] = array(2,4); $pair[5] = array(3,4);解决方案
The simplest solution is to use a nested loop and build combinations as you go, although note that the complexity here is O(n2).
$ids = array(1,2,3,4,4); $combinations = array(); $ids = array_unique($ids); // remove duplicates $num_ids = count($ids); for ($i = 0; $i < $num_ids; $i++) { for ($j = $i+1; $j < $num_ids; $j++) { $combinations[] = array($ids[$i], $ids[$j]); } }See this in action at www.ideone/9wzvP
更多推荐
拆分数组唯一对
发布评论