其他分享
首页 > 其他分享> > 【Swift】LeedCode 好数对的数目

【Swift】LeedCode 好数对的数目

作者:互联网

【Swift】LeedCode 好数对的数目
由于各大平台的算法题的解法很少有Swift的版本,小编这边将会出个专辑为手撕LeetCode算法题。新手撕算法。请包涵!!!

给你一个整数数组 nums 。

如果一组数字 (i,j) 满足 nums[i] == nums[j] 且 i < j ,就可以认为这是一组 好数对 。

返回好数对的数目。

示例 1:
输入:nums = [1,2,3,1,1,3]
输出:4
解释:有 4 组好数对,分别是 (0,3), (0,4), (3,4), (2,5) ,下标从 0 开始
示例 2:
输入:nums = [1,1,1,1]
输出:6
解释:数组中的每组数字都是好数对
示例 3:
输入:nums = [1,2,3]
输出:0

提示:
1 <= nums.length <= 100
1 <= nums[i] <= 100

Swift解法如下:

class Solution {
    func numIdenticalPairs(_ nums: [Int]) -> Int {
        var sum = 0
        for index in 0..<nums.count{
            for index2 in index+1..<nums.count{
                if nums[index]==nums[index2]{
                    sum = sum + 1
                }
            }
        }
        return sum
    }
}

标签:index,好数,示例,sum,nums,LeedCode,Swift
来源: https://blog.csdn.net/weixin_46681371/article/details/122630063