[LeetCode演算法 #219]  圖解 Contains Duplicate II (Sliding Window)

內容目錄

題目

先來看 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] <= 109
  • 0 <= k <= 105

解題思路

建立一個空的 List 名為 templist ,每一次迴圈都判斷 templist 的長度並保持其長度不大於 k,並判斷 templist 中有沒有與當前元素相同的數值,有則回傳 true 。

圖解 LeetCode #219  Contains Duplicate II (Sliding Window演算法)
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;
    }
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *