1512. Number of Good Pairs

LeetCode easy original: C# #array #csharp #easy #leetcode
Le texte du problème est traduit du russe pour la langue sélectionnée. Le code reste inchangé.

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

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

Exemple:

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.

C# solution

correspondant/original
public class Solution {
    public int NumIdenticalPairs(int[] nums) {
        int ans = 0;
        for (int i = 0; i < nums.Length; i++) {
            for (int j = i + 1; j < nums.Length; j++) {
                if (nums[i] == nums[j]) {
                    ans++;
                }
            }
        }
        return ans;
    }
}

C++ solution

brouillon automatique, à relire avant soumission
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int NumIdenticalPairs(vector<int>& nums) {
        int ans = 0;
        for (int i = 0; i < nums.size(); i++) {
            for (int j = i + 1; j < nums.size(); j++) {
                if (nums[i] == nums[j]) {
                    ans++;
                }
            }
        }
        return ans;
    }
}

Java solution

correspondant/original
class Solution {
    public int numIdenticalPairs(int[] nums) {
        int ans = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] == nums[j]) {
                    ans++;
                }
            }
        }
        return ans;
    }
}

JavaScript solution

correspondant/original
var numIdenticalPairs = function(nums) {
    let ans = 0
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            if (nums[i] === nums[j]) {
                ans++
            }
        }
    }
    return ans
}\

Python solution

correspondant/original
class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:
        ans = 0
        for i in range(len(nums)):
            for j in range(i + 1, len(nums)):
                if nums[i] == nums[j]:
                    ans += 1
        return ans

Go solution

correspondant/original
func numIdenticalPairs(nums []int) int {
    ans := 0
    for i := 0; i < len(nums); i++ {
        for j := i + 1; j < len(nums); j++ {
            if nums[i] == nums[j] {
                ans++
            }
        }
    }
    return ans
}

Algorithm

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

2⃣Итерируйте i от 0 до nums.length:

Итерируйте j от i + 1 до nums.length:

Если nums[i] == nums[j], увеличьте ans на 1.

3⃣return ans.

😎

Vacancies for this task

offres actives with overlapping task tags are affichés.

Toutes les offres
Il n'y a pas encore d'offres actives.