拆分数组唯一对

编程入门 行业动态 更新时间:2024-10-06 04:10:08
本文介绍了拆分数组唯一对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

说我先从一个简单的数组(可以是任何长度的理论上):

$ 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

更多推荐

拆分数组唯一对

本文发布于:2023-11-30 15:26:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650503.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!