1. 程式人生 > 其它 >【Lintcode】1319. Contains Duplicate II

【Lintcode】1319. Contains Duplicate II

技術標籤:# 棧、佇列、串及其他資料結構leetcodehashmap演算法

題目地址:

https://www.lintcode.com/problem/contains-duplicate-ii/description

給定一個數組 A A A,再給定一個整數 k k k,問是否有兩個不同位置的相同數的下標之差的絕對值小於等於 k k k

用雜湊表存每個數出現的最後一次位置,當遍歷到 A [ i ] A[i] A[i]的時候先看一下之前是否出現過,出現過則看一下下標差是否小於等於了 k k k。程式碼如下:

import java.util.HashMap;
import java.util.
Map; 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<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) { return true; } map.
put(nums[i], i); } return false; } }

時空複雜度 O ( n ) O(n) O(n)