Domanda di colloquio di Tripadvisor

Find number of pairwise elements in an array with difference k.

Risposte di colloquio

Anonimo

29 ott 2014

Assuming no duplicates, sort an array, iterate through it and find a number a[i]+k, code: public void find(int[]a, int k){ if(a==null||a.length==0)return; if(k == 0){ //since the elements are distinct return; } Arrays.sort(a); for(int i = 0; i =0){ System.out.println(a[i] + " " + a[idx]); } } }

Anonimo

20 nov 2015

No sorting required.. use hash map. it is O(n) algorithm

Anonimo

20 set 2018

def find(nums, k): dic = {} res = [] for i in nums: if i not in dic: dic[k+i]=i else: res.append([dic[i],i]) return res nums = [x for x in range(1,11)] print find(nums, 3)