master
 1<<-DOC
 2Given an array of integers nums and an integer k,
 3determine whether there are two distinct indices i and j
 4in the array where nums[i] = nums[j] and the
 5absolute difference between i and j is less than or equal to k.
 6
 7Example
 8
 9For nums = [0, 1, 2, 3, 5, 2] and k = 3, the output should be
10containsCloseNums(nums, k) = true.
11
12There are two 2s in nums, and the absolute difference between their positions is exactly 3.
13
14For nums = [0, 1, 2, 3, 5, 2] and k = 2, the output should be
15
16containsCloseNums(nums, k) = false.
17
18The absolute difference between the positions of the two 2s is 3, which is more than k.
19
20Input/Output
21
22[time limit] 4000ms (rb)
23[input] array.integer nums
24
25Guaranteed constraints:
260  nums.length  55000,
27-231 - 1  nums[i]  231 - 1.
28
29[input] integer k
30
31Guaranteed constraints:
320  k  35000.
33
34[output] boolean
35DOC
36
37describe "#contains_close_numbers" do
38  def diff(x)
39    1.upto(x.size - 1).map { |n| (x[n] - x[n-1]).abs }
40  end
41
42  def contains_close_numbers(numbers, k)
43    return numbers[0] == numbers[1] if numbers.size == 2
44
45    items = Hash.new { |hash, key| hash[key] = [] }
46    numbers.each_with_index do |number, index|
47      items[number].push(index)
48      return true if diff(items[number]).find { |x| x <= k }
49    end
50
51    false
52  end
53
54  def contains_close_numbers(numbers, k)
55    items = {}
56    numbers.each_with_index do |number, index|
57      puts items.inspect
58      return true if items[number] && (index - items[number]) <= k
59      items[number] = index
60    end
61    false
62  end
63
64  [
65    { nums: [0, 1, 2, 3, 5, 2], k: 3, x: true },
66    { nums: [0, 1, 2, 3, 5, 2], k: 2, x: false },
67    { nums: [], k: 0, x: false },
68    { nums: [99, 99], k: 2, x: true },
69    { nums: [2, 2], k: 3, x: true },
70    { nums: [1, 2], k: 2, x: false },
71    { nums: [1, 2, 1], k: 2, x: true },
72    { nums: [1, 0, 1, 1], k: 1, x: true },
73    { nums: [1, 2, 1], k: 0, x: false },
74    { nums: [1, 2, 1], k: 1, x: false },
75    { nums: [1], k: 1, x: false },
76    { nums: [-1, -1], k: 1, x: true },
77    { nums: [1,2,3,4,1], k: 5, x: true },
78  ].each do |x|
79    it do
80      expect(contains_close_numbers(x[:nums], x[:k])).to eql(x[:x])
81    end
82  end
83end