把一個數組向右迴圈移動k位要求時間複雜度為O(n)

來源:互聯網
上載者:User

標籤:

   今晚做了下某公司的網路筆試題,好久沒刷題了,現在渣得要死,裡面有道程式設計題是 把一個數組向右迴圈移動k位要求時間複雜度為O(n) 給的方法定義為 

public void solution(int a[],int length,int k)

我當時覺得挺容易的,結果一寫出來發現只能移一位。。。

public void solution(int []a,int length,int k){    int temp=a[length-1];    for(int j=length-1;j>0;j--){        a[j]=a[j-1];    }    a[0]=temp;}

然後發現再加個迴圈不就可以移動k位了嗎?。。可是時間複雜度為O(k*n)了。。最後O(n)的演算法有問題沒時間了就用了這個。。

public void solution(int []a,int length,int k){    for(int i=0;i<k;i++){            int temp=a[length-1];//這裡最後還寫錯了沒減一。。        for(int j=length-1;j>0;j--){            a[j]=a[j-1];        }            a[0]=temp;    }}   

剛才突然想起,其實可以直接把第一個數往右移k位,第二位跟在第一個數後面,第三個跟著第二個後面不就可以了嗎。。。

 

#include<iostream.h>void convert(int a[], int start, int end){    int k, temp;    for (k = 0; k < (end-start+1)/2; k++)    {        temp = a[start+k];        a[start+k] = a[end-k];        a[end-k] = temp;    }} void yiwei(int a[], int n, int k){    convert(a,0,k-1);//先將數組前k個數逆置(0~k-1),    convert(a,k,n-1);//先將數組後n-k個數逆置(k~n-1),    convert(a,0,n-1);//先將整個數組逆置,} void main(){    int a[6] = {1,2,3,4,5,6};    yiwei(a,6,2);    for (int i = 0; i < 6; i++)        cout << a[i] << ‘\t‘;}

 

把一個數組向右迴圈移動k位要求時間複雜度為O(n)

聯繫我們

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