1

给定一个整数数组 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)
4

2 回答 2

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
}
于 2016-04-21T20:08:52.963 回答
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
    }
}
于 2016-04-21T20:11:57.327 回答