C++時間復雜度為O(n)隨機生成不重復的數代碼
#include<stdio.h>include <time.h>
include "iostream"
include <math.h>
define N 53
using namespace std;
//print array void display(int *a) { for (int i =0;i<N;i++) { cout<<" "<<a[i]<<" "; }
}
int main(void) {
int b[N],a[N]; for (int i =0;i<N;i++) { b[i] = i+1; } // random(a); srand((unsigned)time(NULL)); int MaxIndex = N; for ( i= 0;i<N;i++) { // int index = (int)rand()%MaxIndex;//隨機一個 0 - 52的index a[i] = b[index]; //隨機到的數字給a[i],i from 0 to N-1 b[index] = b[MaxIndex-1]; MaxIndex--; } display(a); return 0;
} </pre>
本文由用戶 kdloeki 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!