Given an unsorted array and two numbers, find the minimum distance between them. For example, if the array is {1,2, 10, 2, 3, 5, 2, 1, 5} distance between 2 and 5 is 1

#include <stdio.h>
#include <algorithm>
#include <limits.h>

int minDist(int a[], int n, int b, int c) {

int ret = INT_MAX, cur = -1;


while(n--) {

if(a[n] == b || a[n] == c) {

if(cur != -1 && a[cur] != a[n]) {

ret = std::min(ret, cur - n);
}
cur = n;

}

}

return ret;
}


int main() {

int a[] = {1, 2, 10, 2, 3, 5, 2, 1, 5};


printf("%d\n", minDist(a, sizeof(a)/sizeof(int), 2, 5));
return 0;
}
Advertisements

5 thoughts on “Given an unsorted array and two numbers, find the minimum distance between them. For example, if the array is {1,2, 10, 2, 3, 5, 2, 1, 5} distance between 2 and 5 is 1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s