2016-04-21 14 views
1

给定一个整数nums和一个整数k的数组。找出数组中是否有两个不同的索引i和j,使得nums [i] = nums [j],并且i和j之间的差值至多为k。算法:检查Swift数组中的重复

它应该给我真实的,但它给了我虚假。

任何帮助,我欣赏它。非常感谢。

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) 

回答

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 
    } 
} 
+0

非常感谢!这工作完美!欣赏它。 – Tang

+0

我已将你的答案分享给其他社区。希望可以帮助别人。再次感谢您的帮助! – Tang

+0

没问题。别客气 :) – iyuna

1

你永远不添加任何字典:

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 
} 
+0

太谢谢你了!我会看看它!欣赏! – Tang