【Leetcode Algorithm】Contains Duplicate II



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

代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if(k<0){
            return false;
        }
        //通過HashMap來比較是否有重複值
        HashMap numsToHashMap = new HashMap();
        for(int n=0;n<nums.length;n++){
            //如果有重複值且重複值索引之間的差值不大於k,則返回true
            if(numsToHashMap.containsKey(nums[n])&&(n-(int)numsToHashMap.get(nums[n])<=k)){
                return true;
            }
            //否則,則將該值以及其索引存入HashMap
            numsToHashMap.put(nums[n],n);
        }
        return false;
    }
}

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

代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if(k<0){
            return false;
        }
        //通過HashMap來比較是否有重複值
        HashMap numsToHashMap = new HashMap();
        for(int n=0;n<nums.length;n++){
            //如果有重複值且重複值索引之間的差值不大於k,則返回true
            if(numsToHashMap.containsKey(nums[n])&&(n-(int)numsToHashMap.get(nums[n])<=k)){
                return true;
            }
            //否則,則將該值以及其索引存入HashMap
            numsToHashMap.put(nums[n],n);
        }
        return false;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章