/*
This is a free Program, You can modify or redistribute it under the terms of GNU
*Description: 2011年Microsoft一道笔试题, 给定一维整数数组,找到数组里两两数之差绝对值最小的值
*Language: C++
*Development Environment: VC6.0
*Author: Wangzhicheng
*E-mail: 2363702560@qq.com
*Date: 2013/3/16
*/
#include <iostream>
#include <cstdlib>
#include <vector>
#include <ctime>
#include <cmath>
#include <algorithm>
using namespace std;
class Solution {
private:
int N;
vector<int>array;
int x, y;
int min;
public:
Solution(int n) {
if(n <= 0) {
perror("arguments error!\n");
}
N = n;
int i;
srand(unsigned(time(0)));
for(i=0; i<n; i++) {
int x = rand() % n;
array.push_back(x);
cout<<x<<" ";
}
cout<<endl;
x = array[0];
y = array[1];
min = fabs(x-y);
}
/*
* 方法一: 采用枚举法, 时间复杂度为O(n*n)
*/
void JustDoIt1() {
int i, j;
for(i = 0; i< N - 1; i++) {
for(j = i + 1; j < N; j++) {
if(fabs(array[i] - array[j]) < min) {
x = i;
y = j;
min = fabs(array[i] - array[j]);
}
}
}
}
/*
* 方法二: 先快速排序, 后相邻两数两两比较, 时间复杂度为O(n*lg(n))
*/
void JustDoIt2() {
vector<int>v;
v.assign(array.begin(), array.end());
sort(v.begin(), v.end());
int x, y;
int min;
x = v[0];
y = v[1];
min = fabs(x-y);
int i;
for(i = 1; i< N; i++) {
if(fabs(v[i] - v[i-1]) < min) {
x = i;
y = i - 1;
min = fabs(v[i] - v[i-1]);
}
}
cout<<v[x]<<"-"<<v[y]<<"的绝对值最小,是"<<min<<endl;
}
void show() const {
cout<<array[x]<<"-"<<array[y]<<"的绝对值最小,是"<<min<<endl;
}
};
void main() {
Solution s(10);
s.JustDoIt1();
s.show();
s.JustDoIt2();
}