I. Details of the problem:
Given an integer array nums and an integer target value target, find the two integers in the array and the target value target and return their array subscripts. Can you think of an algorithm whose time complexity is less than O(n2)?
Ii. My answer:
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { let arr = []; For (let I = 0; i < nums.length; I ++){for(let j = I + 1; j < nums.length; If (nums[I] + nums[j] == target){arr. Push (I) arr. // Get the subscript array}}}};Copy the code
Iii. Reference Answers:
@param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function(nums, target) { let hash = [] for (let i = 0; i < nums.length; i++) { if (hash[nums[i]] ! Return [hash[nums[I]], I]} else {hash[target-nums [I]] = I // Save the expected value of the current element and the current index to hash}} return []};Copy the code
Iv. Summary and suggestions: Time complexity of the algorithm should be considered comprehensively. Time complexity: T(n) = O(f(n)) Space complexity: S(n) = O(f(n))