算法:检查Swift数组中的重复

时间:2016-04-21 18:26:34

标签: swift2.2

给定一个整数nums数组和一个整数k。找出数组中是否有两个不同的索引i和j,使得nums [i] = nums [j],i和j之间的差异最多为k。

它应该给我真实,但它给了我错误。

任何帮助,我很感激。非常感谢你。

class Solution
{
    func containsNearbyDuplicate (nums: [Int], _ k: Int) -> Bool
    {
        var dict = [Int:Int]()
        for i in 0..<nums.count
        {
            if dict[nums[i]] != nil
            {
                if dict.values.contains(nums[i]) && (i - dict[nums[i]]! <= k)
                {
                    return true
                }
                else
                {
                    dict[i] = nums[i]
                }
           }

        }
        return false
    }
}

let test1 = Solution()
//var haha = [1,2,1,5,6,7,6,8,7,5]
//var haha = [1]
//var haha = [1,2]
//var haha = [1,2,3,5,6,8]
var haha = [-1,-1]
var result = test1.containsNearbyDuplicate(haha,1)
print(result)

2 个答案:

答案 0 :(得分:1)

你永远不会向dict添加任何东西:

func containsNearbyDuplicate (nums: [Int], _ k: Int) ->Bool
{

    var dict = [Int:Int]()

    for i in 0..<nums.count
    {

        if dict[nums[i]] != nil // This prevents anything to be added to dict
        {
            if dict.values.contains(nums[i]) && (i - dict[nums[i]]! <= k)
            {
                return true
            }

            else
            {
                dict[i] = nums[i] // This is never executed because of the above if above
            }
        }
    }
    return false
}

答案 1 :(得分:0)

试试这个:

class Solution {
    func containsNearbyDuplicate (nums: [Int], _ k: Int) ->Bool {
        var dict = [Int:Int]()
        for i in 0..<nums.count {
            if let firstIndex = dict[nums[i]] where i - firstIndex <= k {
                return true
            } 
            dict[nums[i]] = i
        }
        return false
    }
}