Skip to content

Commit 6db0f30

Browse files
committed
practice to solve
1 parent d24be09 commit 6db0f30

1 file changed

Lines changed: 42 additions & 4 deletions

File tree

javascript/index.js

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1459,15 +1459,53 @@ The least frequent digits in n are 7, 2, and 5; each appears only once.
14591459
* @return {number[]}
14601460
*/
14611461
var solveQueries = 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+
let mapNums = new Map();
1471+
for(let i = 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+
let arr = new Array(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+
function binarySearch(arr,target){
1487+
let left = 0,right = arr.length - 1;
1488+
while(left <= right){
1489+
let mid = left + Math.floor((right - left) / 2);
1490+
1491+
if(arr[mid] === target){
1492+
return mid;
1493+
}else if(arr[mid] > target){
1494+
right--;
1495+
}else{
1496+
left++;
1497+
}
1498+
}
1499+
return -1;
1500+
}
1501+
14631502
};
1464-
// let nums = [1,3,1,4,1,3,2], queries = [0,3,5];
1503+
let nums = [1,3,1,4,1,3,2], queries = [0,3,5];
14651504
/*
14661505
Output: [2,-1,3]
14671506
Explanation:
14681507
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.
14691508
Query 1: The element at queries[1] = 3 is nums[3] = 4. No other index contains 4, so the result is -1.
14701509
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).
14711510
*/
1472-
1473-
1511+
console.log(solveQueries(nums,queries));

0 commit comments

Comments
 (0)