2016-10-22 57 views
0

如何检查阵列中每一对元素是否都存在那些对的乘法应答。阵列元件产品

Example: 
example 1=a={1,2}; here 2*1=2 which exist in array 
example 2=a={1,2,1}; here 1*2=2 so 2 exist,2*1=2 so this also exist. 
example 3=a={3,4}; here 3*4=12 which doesn't exist in this array 
so how we can check that this type of array exist or not. 

回答

0

$elements = array( array(1,2), array(1,2,1), array(3,4), );

foreach ($elements as $subElements) { foreach ($subElements as $element) { $product = current($subElements) * next($subElements); if (in_array($product, $subElements)) { echo $product.' exists<br>'; } } }

0
  1. 贮存于unordered_map(C++)或散列映射(爪哇)
  2. 运行所有元件中的两个for-loop[first_entry, last_entry)作为外(outer_entry, last_entry]作为内循环,做键的总和并检查总和是否为pr esent在地图中。如果未找到,请跳出最外面的循环,并返回Doesn't exist
  3. 否则返回Exist

创建地图将采取O(N)和检查对总和的存在将采取O(N^2)

所以,TC:O(N^2)

0

这样的阵列必须有所有,但一个元素等于否则数组将会无限大。