leetcode-1
02-03
//給定一個整數數組和一個值target,求兩個下標i、j,使得a[i] + a[j] = target,返回下標。
var twoSum = function(nums, target){ntvar arr = [];nnt//nums 非法值ntif(!(Array.isArray(nums) && nums.length > 1)){nttreturn arr;nt}nt//target 非法值ntif(isNaN(parseFloat(target))){nttreturn arr;nt}nt//暴力破解(O(N^2))ntfor(var i=0; i<nums.length; i++){nttvar a = nums[i];nnttfor(var j=i+1; j<nums.length; j++){nntttvar b = nums[j];nntttif((a + b) === target){nttttarr.push(i, j);nttttreturn arr;nttt}nntt}nt}nntreturn arr;n};nvar res = twoSum([2, 7, 11, 15], 22);n
思路沒什麼特別,循環暴力破解
推薦閱讀:
※leetcode也開始收費了,大家怎麼看?
※單鏈表翻轉?
※LeetCode 15. 3Sum
TAG:LeetCode |