【面試題】尋找數組中的某個結點

來源:互聯網
上載者:User
題目:

原有一個有序數組(假設升序),分成前後兩部分,然後將這兩部分交換得到一個新的數組。寫一個函數,參數是這個新的數組,要求找到數組分開的那個結點,而且要考慮時間複雜度。

解法1:遍曆該數組,找到第一個前一個大於後一個的數,否則返回最後一個數。時間複雜度O(n)。解法2:使用二分尋找,時間複雜度O(lgn)。需要注意的是二分的地方不能使用mid+1,否則會錯過那個結點。
#include <iostream>using namespace std;int find(int a[], int i, int j){if(i<0 || j<0)return -1;if(i>=j)return i;int mid=(i+j)/2;if(mid==i)//j=i+1return i;if(a[mid]>a[i])return find(a,mid,j);//這裡不能換成mid+1,否則會錯過那個節點elsereturn find(a,i,mid-1);}int main(){int a[11]={5,6,7,8,9,10,0,1,2,3,4};//int a[11]={0,1,2,3,4,5,6,7,8,9,10};int len=sizeof(a)/sizeof(int);int index=find(a,0,len-1);if (index!=-1)cout<<"the "<<index<<"th number:"<<a[index]<<endl;}
輸出為:
the 5th number:10

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.