題目
先來看 219. Contains Duplicate II 的題目內容:
Given an integer array nums and an integer k, return trueif there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
Constraints:
1 <= nums.length <= 105-109 <= nums[i] <= 1090 <= k <= 105
解題思路
建立一個空的 List 名為 templist ,每一次迴圈都判斷 templist 的長度並保持其長度不大於 k,並判斷 templist 中有沒有與當前元素相同的數值,有則回傳 true 。

public class Solution {
public bool ContainsNearbyDuplicate(int[] nums, int k) {
List<int> templist= new List<int>();
for(int i=0;i<nums.Length;i++){
if(templist.Count-1>=k){
templist.Remove(templist[0]);
}
if(templist.Contains(nums[i])){
return true;
}
templist.Add(nums[i]);
}
return false;
}
}