Tai Le
BAN USER
Comments (2)
Reputation 0
Page:
1
Comment hidden because of low score. Click to expand.
Comment hidden because of low score. Click to expand.
0
of 0 vote
Because the array is unique, positive and increased sorted, therefore, given a k, for one element, we just need to check k element a head (suppose the difference between two consecutive item is minimum 1)
public static void main (String[] args) throws java.lang.Exception
{
int k = 3;
int arr[] = {1,2,3,5,6,8,9,11,12,13};
findPairs(arr,k);
}
public static void findPairs(int[] arr,int k) {
for(int idx = 0; idx < arr.length; idx++) {
for (int distance = 1; distance <= k && ((idx+distance) < arr.length); distance++) {
if((arr[idx + distance] - arr[idx]) == k) {
System.out.println(arr[idx] + ", " + arr[idx + distance]);
break; // Skip inner loop
}
}
}
}
Page:
1
CareerCup is the world's biggest and best source for software engineering interview preparation. See all our resources.
Could not modify :). Running time will be O(k*n)
- Tai Le October 12, 2015