Given an array of integers and an integer k, find out 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.
Example 1:
Input: nums = [1,2,3,1], k = 3 Output: true
Approach
Java
import java.util.HashMap;public class ContainsDuplicateII {public static void main(String[] args) {int[] nums = { 1, 2, 3, 1 };int k = 3;System.out.println(containsNearbyDuplicate(nums, k));}static boolean containsNearbyDuplicate(int[] nums, int k){HashMap<Integer,Integer> mp=new HashMap<Integer, Integer>();for (int i = 0; i < nums.length; i++){if (mp.containsKey(nums[i])){if ((i - mp.get(nums[i])) <= k)return true;}mp.put(nums[i], i);}return false;}}
C++
#include <bits/stdc++.h>using namespace std;bool containsNearbyDuplicate(vector<int> &nums, int k){unordered_map<int, int> ump;for (int i = 0; i < nums.size(); i++){if (ump.count(nums[i]) == 1){if ((i - ump[nums[i]]) <= k)return true;}ump[nums[i]] = i;}return false;}int main(){vector<int> nums = {1, 2, 3, 1};int k = 3;if (containsNearbyDuplicate(nums, k))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment