【问题标题】:Algorithm: check for duplication in Swift array算法:检查 Swift 数组中的重复项
【发布时间】:2016-04-22 22:24:39
【问题描述】:

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

【问题讨论】:

    标签: swift2.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
    }
    

    【讨论】:

      【解决方案2】:

      试试这个:

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

      【讨论】:

      • 非常感谢!这很完美!欣赏它。
      • 我已将您的答案分享给其他社区。希望可以帮助别人。再次感谢您的帮助!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      相关资源
      最近更新 更多