1. 程式人生 > >【一次過】Lintcode 1319. Contains Duplicate II

【一次過】Lintcode 1319. Contains Duplicate II

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

樣例

Given nums = [1,2,1], k = 0, return false.

解題思路:

由於與下標有關係,所以使用HashMap儲存陣列中的值與對應的下標,將陣列依次掃描儲存進Map中,當遇到有重複值時,判斷這兩值對應下標的絕對值差是否滿足條件,滿足則返回true,否則更新下標值,因為為了讓對後面重複值與它的差儘可能最小,所以需要使其下標保持最前。

public class Solution {
    /**
     * @param nums: the given array
     * @param k: the given number
     * @return:  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
     */
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        // Write your code here
        Map<Integer,Integer> map = new HashMap<>();//key儲存陣列中的值,value儲存對應值的下標
        
        for(int i=0 ; i<nums.length ; i++){
            if(!map.containsKey(nums[i])){ //如果此值第一次出現
                map.put(nums[i],i);
            }else{ //如果碰見相等的值
                int diff = Math.abs(map.get(nums[i]) - i); //相等值的下標絕對值差
                if(diff <= k)
                    return true;
                else
                    map.put(nums[i],i); //更新下標
            }
        }
        
        return false;
    }
}