[經典面試題][阿里]三元組最小距離,試題阿里

來源:互聯網
上載者:User

[經典面試題][阿里]三元組最小距離,試題阿里

題目

已知三個升序整數數組a[l], b[m]和c[n]。請在三個數組中各找一個元素,是的組成的三元組距離最小。三元組的距離定義是:假設a[i]、b[j]和c[k]是一個三元組,那麼距離為:

Distance = max(|a[ I ] – b[ j ]|, |a[ I ] – c[ k ]|, |b[ j ] – c[ k ]|)

請設計一個求最小三元組距離的最優演算法,並分析時間複雜度。

思路

保持三個下標索引 i,j,k,找出a[i],b[j],c[k]裡最小的元素。如果a[i]最小, 則下一次迴圈 i=i+1, 其他兩個索引不變。如果b[j]最小, 則下一次迴圈 j=j+1, 其他兩個索引不變。如果c[k]最小, 則下一次迴圈 k=k+1, 其他兩個索引不變。如此迴圈,直至最小的數對應的下標到達該數組尾部。記錄最小距離。

時間複雜度:O(l+m+m) (每次迴圈總有一個下標走了一步)。

代碼

    /*---------------------------------------------    *   日期:2015-02-21    *   作者:SJF0115    *   題目: 三元組最小距離    *   來源:阿里    *   部落格:    -----------------------------------------------*/    #include <iostream>    #include <climits>    #include <algorithm>    using namespace std;    class Solution {    public:        int MinDistance(int a[],int l,int b[],int m,int c[],int n){            if(l <= 0 || n <= 0 || m <= 0){                return -1;            }//if            int min = INT_MAX;            int dis = 0,first = 0,second = 0,third = 0;            for(int i = 0,j = 0,k = 0;i < l && j < m && k < n;){                dis = max(max(abs(a[i]-b[j]),abs(a[i]-c[k])),abs(b[j]-c[k]));                if(dis < min){                    min = dis;                    first = i;                    second = j;                    third = k;                }//if                if(a[i] < b[j]){                    if(a[i] < c[k]){                        ++i;                    }//if                    else{                        ++k;                    }//else                }//if                else{                    if(b[j] < c[k]){                        ++j;                    }//if                    else{                        ++k;                    }//else                }//else            }//for            cout<<"First->"<<first<<" Second->"<<second<<" Third->"<<third<<endl;            return min;        }    };    int main() {        Solution solution;        int a[] = {5,16,20};        int b[] = {13,14,15,17,35};        int c[] = {19,22,24,29,32,42};        int l = 3,m = 5,n = 6;        int result = solution.MinDistance(a,l,b,m,c,n);        cout<<result<<endl;    }

如果有好的思路,可以留言。。。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.