code(ts): worst best time complexity

pull/196/head
RiverTwilight 2 years ago
parent 8031e0e2c5
commit c53f64d56b

@ -5,7 +5,7 @@
*/
function randomNumbers(n: number): number[] {
nums = Array(n);
let nums = Array(n);
for (let i = 0; i < n; i++) {
nums[i] = i + 1;
}
@ -19,7 +19,7 @@ function randomNumbers(n: number): number[] {
return nums;
}
function findOne(nums) {
function findOne(nums: number[]): number {
for (let i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
return i;
@ -28,7 +28,7 @@ function findOne(nums) {
return -1;
}
function main() {
function main(): void {
for (let i = 0; i < 10; i++) {
let n = 100;
let nums = randomNumbers(n);

@ -2329,7 +2329,7 @@ $$
```js title="worst_best_time_complexity.js"
function randomNumbers(n) {
nums = Array(n);
let nums = Array(n);
for (let i = 0; i < n; i++) {
nums[i] = i + 1;
}
@ -2368,7 +2368,41 @@ $$
=== "TypeScript"
```typescript title="worst_best_time_complexity.ts"
function randomNumbers(n: number): number[] {
let nums = Array(n);
for (let i = 0; i < n; i++) {
nums[i] = i + 1;
}
// 随机打乱数组元素
for (let i = 0; i < n; i++) {
let r = Math.floor(Math.random() * n);
let temp = nums[i];
nums[i] = nums[r];
nums[r] = temp;
}
return nums;
}
function findOne(nums: number[]): number {
for (let i = 0; i < nums.length; i++) {
if (nums[i] == 1) {
return i;
}
}
return -1;
}
function main(): void {
for (let i = 0; i < 10; i++) {
let n = 100;
let nums = randomNumbers(n);
let index = findOne(nums);
console.log(
"\n数组 [ 1, 2, ..., n ] 被打乱后 = [" + nums.join(", ") + "]"
);
console.log("数字 1 的索引为 " + index);
}
}
```
=== "C"

Loading…
Cancel
Save