2016-10-22 94 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

這樣的陣列必須有所有,但一個元素等於否則數組將會無限大。