首页 > 代码库 > 219. 数组重复元素2 Contains Duplicate II

219. 数组重复元素2 Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.


  1. public class Solution {
  2. public bool ContainsNearbyDuplicate(int[] nums, int k) {
  3. Dictionary<int, int> dict = new Dictionary<int, int>();
  4. for (int i = 0; i < nums.Length; i++) {
  5. int index;
  6. if (dict.TryGetValue(nums[i], out index)) {
  7. if (i - index <= k) {
  8. return true;
  9. }
  10. }
  11. dict[nums[i]] = i;
  12. }
  13. return false;
  14. }
  15. }





null


219. 数组重复元素2 Contains Duplicate II