You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: javascript/index.js
+42-4Lines changed: 42 additions & 4 deletions
Original file line number
Diff line number
Diff line change
@@ -1459,15 +1459,53 @@ The least frequent digits in n are 7, 2, and 5; each appears only once.
1459
1459
* @return {number[]}
1460
1460
*/
1461
1461
varsolveQueries=function(nums,queries){
1462
-
1462
+
/**
1463
+
* querise[i] = nums[i]
1464
+
*
1465
+
* Use a HashMap to store the indices of each number in nums. The key should be nums[i], and the value should be a list of indices where nums[i] appears.
1466
+
* Hint 2: For each query, retrieve the stored list of indices for nums[queries[i]].
1467
+
* Hint 3: Use binary search to efficiently find the next occurrence of the number. This reduces the lookup time to O(log N) instead of O(N).
1468
+
*
1469
+
*/
1470
+
letmapNums=newMap();
1471
+
for(leti=0;i<nums.length;++i){
1472
+
// mapNums: key(nums[i]),value(i)
1473
+
if(!mapNums.has(nums[i])){
1474
+
mapNums.set(nums[i],[])
1475
+
}
1476
+
mapNums.get(nums[i]).push(i)
1477
+
}
1478
+
console.log(mapNums)
1479
+
letarr=newArray(nums.length).fill(-1);
1480
+
// for(let i = 0;i < queries.length;++i) {
1481
+
// if(mapNums.has(queries[i])){
1482
+
// console.log(mapNums.get(queries[i]))
1483
+
// }
1484
+
// }
1485
+
// binary search
1486
+
functionbinarySearch(arr,target){
1487
+
letleft=0,right=arr.length-1;
1488
+
while(left<=right){
1489
+
letmid=left+Math.floor((right-left)/2);
1490
+
1491
+
if(arr[mid]===target){
1492
+
returnmid;
1493
+
}elseif(arr[mid]>target){
1494
+
right--;
1495
+
}else{
1496
+
left++;
1497
+
}
1498
+
}
1499
+
return-1;
1500
+
}
1501
+
1463
1502
};
1464
-
// let nums = [1,3,1,4,1,3,2], queries = [0,3,5];
1503
+
letnums=[1,3,1,4,1,3,2],queries=[0,3,5];
1465
1504
/*
1466
1505
Output: [2,-1,3]
1467
1506
Explanation:
1468
1507
Query 0: The element at queries[0] = 0 is nums[0] = 1. The nearest index with the same value is 2, and the distance between them is 2.
1469
1508
Query 1: The element at queries[1] = 3 is nums[3] = 4. No other index contains 4, so the result is -1.
1470
1509
Query 2: The element at queries[2] = 5 is nums[5] = 3. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: 5 -> 6 -> 0 -> 1).
0 commit comments