我得到了一个像array(1,5,3,4,2);
这样的数组
说k=2
,我应该找出差异为2的对的数量。在这种情况下它应该返回3,因为5-3, 4-2, 3-1
这是我尝试过的。它工作正常我循环数组两次O(n^2)
复杂性,我想知道是否有更好的方法来实现这一点。
$arr = array(1,5,3,4,2);
$k =2;
function find_pairs($arr, $k)
{
$count = 0;
for ($i=0 ; $i<= count($arr)-1 ; $i++)
{
for ($j=$i+1; $j <= count($arr)-1 ; $j++)
{
if ($arr[$i]-$arr[$j] == $k || $arr[$j]-$arr[$i]==$k)
{
$count++;
}
}
}
return $count;
}
echo find_pairs($arr, $k);
由于
答案 0 :(得分:1)
当然,有很多方法:
使用排序:
Sort the array arr
Take two pointers, l and r, both pointing to 1st element
Take the difference arr[r] – arr[l]
If value diff is K, increment count and move both pointers to next element
if value diff > k, move l to next element
if value diff < k, move r to next element
return count
复杂度为O(n)的是:
1) Initialize count as 0.
2) Insert all distinct elements of arr[] in a hash map. While inserting,
ignore an element if already present in the hash map.
3) Do following for each element arr[i].
a) Look for arr[i] + k in the hash map, if found then increment count.
b) Look for arr[i] - k in the hash map, if found then increment count.
c) Remove arr[i] from hash table.
无论如何,您可以参考此link了解更多信息。
答案 1 :(得分:0)
当然可以。您可以使用以下内容:
这具有O(n log n)复杂度。
答案 2 :(得分:0)
呀。您可以使用unordered_set。详述如下:
1. Insert the all elements of array into unordered_set.
2. Initialize count=0
3. for loop i=0 to i=n where n is the length of array
if arr[i]+k is found then increment count
4. Return count.
上述程序的复杂程度为O(N)。
Php code Snippet:
function find_pairs($a, $k)
{
$num = array_flip($a);
$count = 0;
foreach($num as $n => $_unused)
{
if(isset($num[$n + $k]))
{
$count++;
}
}
return $count;
}
答案 3 :(得分:-1)
给出一个整数n,使用递归计数并返回给定整数中存在的零个数。
def count0(n):
if n==0:
return 0
if n%10==0:
return 1+count0(int(n/10))
else:
return count0(int(n/10))
n=int(input())
print(count0(n))