所以在 LeetCode 上,我需要回傳等于目標數的兩個數之和。這是 leetcode“簡單”型別。我以前從未使用過 leetcode,所以我決定嘗試一下。馬上,我能夠解決這個問題,但我的解決方案是無意義的,因為它檢查陣列中的每個數字。因此,如果輸入是一百萬位數字,那么它將為每個數字檢查一百萬次。
值得注意的是,雖然我的程式有效,但由于時間限制,它可以提交。
我不確定優化這個的數學解決方案是什么。我目前正在再次學習數學,以學習我的弱項。
代碼:
var twoSum = function(nums, target) {
let total = [];
let inc = 1;
let intVal = 0;
let startingPos = nums[intVal];
let nextPos = nums[inc];
for(let x = 0; x < nums.length; x ){
// Do not check the value of position 1 with position 2
if(nums.indexOf(startingPos) === nums.lastIndexOf(nextPos)){
nextPos ;
}
if(startingPos nextPos === target){
console.log(`First Value ${startingPos}`)
console.log(`Second Value ${nextPos}`)
console.log(`Target ${target}`)
// A match has been found
return [nums.indexOf(startingPos), nums.lastIndexOf(nextPos)];
} else{
// Move to next number if index 1 is not eql
// nextPos ;
let nextPosIndex = nums[inc];
nextPos = nums[inc];
console.log(`Values [${startingPos}], [${nextPos}]`)
console.log("No Matches");
// Increment the next value to check
inc ;
// Reset loop if no match is found from 2nd position
if(x == (nums.length - 1)){
// Increment the initial value in first pos
intVal ;
startingPos = nums[intVal];
// Reset values to check new numbers
x = 0;
inc = 1;
}
// check if we exhausted all options
if(startingPos === undefined){
return "No Matches.";
}
}
}
};
twoSum([5, 2, 5, 5, 1, 3, 6, 8, 4, 3, 2, 7], 14)
-- 在繼續解決更多問題之前,我恐怕會陷入選擇最不合邏輯的解決問題方式的回圈中。
我能做些什么來修改這個問題以快速檢查兩個值是否等于目標。
這是一個實時編譯器示例:https : //replit.com/@FPpl/SafeHeartfeltArchitect#index.js
uj5u.com熱心網友回復:
在迭代一個數字時,您可以將與目標相匹配的值放入一個集合中(帶O(1)查找)。例如,如果您迭代一個數字 5,而目標是 20,則將 15 放入集合中。
在迭代程序中,如果要迭代的數字已經存在于集合中,那么您就有了之前找到的一個匹配項,并且您可以回傳這兩個索引。
const twoSum = function(nums, target) {
// For this Map, the key is the number which, if found again, is a match
// eg, if target is 20, and the number 5 is iterated over
// the key will be 15
// The value is the index of the prior number found - eg, index of 5
const valuesAlreadyFound = new Map();
for (let i = 0; i < nums.length; i ) {
const num = nums[i];
if (valuesAlreadyFound.has(num)) {
// We have a match, get both indicies:
console.log('Match for values', target - num, num);
return [valuesAlreadyFound.get(num), i];
}
// This wasn't a match. Identify the number which, when paired, is a match
const matchNeeded = target - num;
valuesAlreadyFound.set(matchNeeded, i);
}
return 'No match';
};
console.log('Indicies found:', twoSum([5, 2, 5, 5, 1, 3, 6, 8, 4, 3, 2, 7], 14));
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/312862.html
標籤:javascript 算法 数学
