public class GFG {
/* Java program to Check if a given array contains duplicate elements within k distance from each other */ public static boolean checkDuplicatesWithinK(int[] arr, int n, int k) {
// traversing the input array for (int i = 0; i < n; i++) { int j = i + 1; int range = k; // 在下 k-1 个元素中搜索其 //是否存在重复元素 while (range > 0 && j < n) { if (arr[i] == arr[j]) { return true; } j++; range--; } } return false; }
// 测试上述方法的驱动程序方法 public static void main(String[] args) { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.length; if (checkDuplicatesWithinK(arr, n, 3)) { System.out.print("Yes"); } else { System.out.print("No"); } } }
Python: # Python3 program to Check if a given array contains duplicate # elements within k distance from each other def checkDuplicatesWithinK(arr, n, k):
# 遍历输入数组 for i in range(n): j = i + 1 range_ = k # 在下 k-1 个元素中查找是否存在重复 # while (range_ > 0 and j < n): if (arr[i] == arr[j]): return True j += 1 range_ -= 1
return False
# Driver method to test above method
arr = [10, 5, 3, 4, 3, 5, 6] n = len(arr) if (checkDuplicatesWithinK(arr, n, 3) == True): print("Yes") else: print("No")
C#
/* C# program to Check if a given array contains duplicate elements within k distance from each other */ using System; using System.Collections.Generic;
class GFG { static bool checkDuplicatesWithinK(int[] arr, int n, int k) { // traversing the input array for (int i = 0; i < n; i++) { int j = i + 1; int range = k; // searching in next k-1 elements if its // duplicate is present or not while (range > 0 && j < n) { if (arr[i] == arr[j]) return true; j++; range--; } } return false; }
// Driver code public static void Main(String[] args) { int[] arr = { 10, 5, 3, 4, 3, 5, 6 }; int n = arr.Length; if (checkDuplicatesWithinK(arr, n, 3)) Console.WriteLine("Yes"); else Console.WriteLine("No"); } }
Javascript
class GFG { // javascript program to Check if a given array contains // duplicate elements within k distance from each other static checkDuplicatesWithinK(arr, n, k) { // traversing the input array for (var i=0; i < n; i++) { var j = i + 1; var range = k; //在下 k-1 个元素中搜索,如果其 // 是否存在重复 while (range > 0 && j < n) { if (arr[i] == arr[j]) { return true; } j++; range--; } } return false; } // Driver method to test above method static main(args) { var arr = [10, 5, 3, 4, 3, 5, 6]; var n = arr.length; if (GFG.checkDuplicatesWithinK(arr, n, 3)) { console.log("Yes"); } else { console.log("No"); } } } GFG.main([]);
|