Skip to content

Commit 1e517c6

Browse files
committed
try to solve 3 kyu
1 parent f6c8042 commit 1e517c6

1 file changed

Lines changed: 51 additions & 13 deletions

File tree

javascript/index.js

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { format } from 'node:path';
33
import {ExecutionTimer} from './time.js';
44
import assert from 'node:assert/strict';
5+
import { count } from 'node:console';
56

67
/*
78
22. Generate Parentheses
@@ -1169,20 +1170,57 @@ var specialTriplets = function(nums) {
11691170
*/
11701171
function smaller(arr) {
11711172
// 這方法ok,但不適用於large test cases
1172-
let ans = [];
1173-
for(let i = 0;i < arr.length;++i) {
1173+
// let ans = [];
1174+
// for(let i = 0;i < arr.length;++i) {
1175+
// let count = 0;
1176+
// for(let j = 0;j < arr.length;j++) {
1177+
// // if(arr[i] === arr[j]){
1178+
// // continue;
1179+
// // }
1180+
// if(arr[i] > arr[j]){
1181+
// count++;
1182+
// }
1183+
// }
1184+
// ans[i] = count;
1185+
// }
1186+
// return ans;
1187+
1188+
return arr.map((current, i) => {
11741189
let count = 0;
1175-
for(let j = i + 1;j < arr.length;j++) {
1176-
if(arr[i] === arr[j]){
1177-
continue;
1178-
}
1179-
if(arr[i] > arr[j]){
1180-
count++;
1181-
}
1182-
}
1183-
ans[i] = count;
1184-
}
1185-
return ans;
1190+
// 比較當前元素右邊所有的元素
1191+
for (let j = 0; j < arr.length; j++) {
1192+
if (arr[j] < current) {
1193+
count++;
1194+
}
1195+
}
1196+
return count;
1197+
});
1198+
1199+
// binary search
1200+
// const result = new Array(arr.length).fill(0);
1201+
// const sortedArray = [];
1202+
1203+
// // 從右往左處理每個元素
1204+
// for (let i = arr.length - 1; i >= 0; i--) {
1205+
// const current = arr[i];
1206+
1207+
// // binary search
1208+
// let left = 0;
1209+
// let right = sortedArray.length;
1210+
1211+
// while (left < right) {
1212+
// const mid = Math.floor((left + right) / 2);
1213+
// if (sortedArray[mid] < current) {
1214+
// left = mid + 1;
1215+
// } else {
1216+
// right = mid;
1217+
// }
1218+
// }
1219+
// result[i] = left;
1220+
1221+
// sortedArray.splice(left, 0, current);
1222+
// }
1223+
// return result;
11861224
}
11871225
console.log(assert.deepEqual(smaller([5, 4, 7, 9, 2, 4, 1, 4, 5, 6]), [5, 2, 6, 6, 1, 1, 0, 0, 0, 0]));
11881226
console.log(assert.deepEqual(smaller([5, 4, 3, 2, 1]), [4, 3, 2, 1, 0]))

0 commit comments

Comments
 (0)