TGViewer
PHP | LeetCode PHP | LeetCode @easy_php_task · 1.33K subscribers
Post #899 149
Задача: 1512. Number of Good Pairs
Сложность: easy

Дан массив целых чисел nums, верните количество хороших пар.

Пара (i, j) называется хорошей, если nums[i] == nums[j] и i < j.

Пример:
Input: nums = [1,2,3,1,1,3]
Output: 4
Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.


👨‍💻 Алгоритм:

1⃣Инициализируйте переменную ans значением 0.

2⃣Итерируйте i от 0 до nums.length:
Итерируйте j от i + 1 до nums.length:
Если nums[i] == nums[j], увеличьте ans на 1.

3⃣Верните ans.

😎 Решение:
class Solution {
function numIdenticalPairs($nums) {
$ans = 0;
for ($i = 0; $i < count($nums); $i++) {
for ($j = $i + 1; $j < count($nums); $j++) {
if ($nums[$i] == $nums[$j]) {
$ans++;
}
}
}
return $ans;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_php_task
  1. Oct 16, 2026Задача: 760. Find Anagram Mappings Сложность: easy Вам даны два целочисленных массива nums…
  2. Oct 15, 2026Задача: 474. Ones and Zeroes Сложность: medium Дан массив двоичных строк strs и два целых…
  3. Oct 15, 2026Задача: 1273. Delete Tree Nodes Сложность: medium Дерево, укорененное в узле 0, задано сле…
  4. Oct 14, 2026Задача: 724. Find Pivot Index Сложность: easy Если задан массив целых чисел nums, вычислит…
  5. Oct 14, 2026Задача: 674. Longest Continuous Increasing Subsequence Сложность: easy Дан неотсортированн…
  6. Oct 13, 2026Задача: 899. Orderly Queue Сложность: hard Вам дана строка s и целое число k. Вы можете вы…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →