###### tags: `Week_1`, `LeetCode 75 Plan` # Recommended Topics .. ## [1. Two Sum](https://leetcode.com/problems/two-sum/) harry: ```typescript= function twoSum(nums: number[], target: number): number[] { let seenIndex = {}; for(let i = 0; i < nums.length; i++) { let remain = target - nums[i]; let foundIndex = seenIndex[remain]; if(foundIndex!==undefined) { return [foundIndex, i]; } else { seenIndex[nums[i]] = i; } } }; ``` sam: ```python= class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: diff_map = dict() for i, num in enumerate(nums): if num not in diff_map: diff_map[target-num] = i else: return [i, diff_map[num]] ``` ## [88. Merge Sorted Array](https://leetcode.com/problems/merge-sorted-array/) harry: ```ruby= # @param {Integer[]} nums1 # @param {Integer} m # @param {Integer[]} nums2 # @param {Integer} n # @return {Void} Do not return anything, modify nums1 in-place instead. def merge(nums1, m, nums2, n) return nums1 if n.zero? if m.zero? n.times.each {|i| nums1[i] = nums2[i] } return nums1 end n.times do |i| nums1[i+m] = nums2[i] end nums1.sort! end ``` ```ruby= # M+N def merge(nums1, m, nums2, n) while n > 0 nums1[m + n - 1], m, n = if m > 0 && nums1[m - 1] > nums2[n - 1] [nums1[m - 1], m - 1, n] else [nums2[n - 1], m, n - 1] end end end ``` ```ruby= # M+N # @param {Integer[]} nums1 # @param {Integer} m # @param {Integer[]} nums2 # @param {Integer} n # @return {Void} Do not return anything, modify nums1 in-place instead. def merge(nums1, m, nums2, n) while n.positive? if m.positive? && nums1[m-1] > nums2[n-1] nums1[m+n-1] = nums1[m-1] m-=1 else nums1[m+n-1] = nums2[n-1] n-=1 end end end ``` Sam: ```python= 1. Time = O(N+Nlog(N)) class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ start_replace_index = 0 for i in range(len(nums1)-1, -1, -1): # print(i, nums1[i]) if nums1[i] != 0: start_replace_index = i + 1 break # print(start_replace_index) for num in nums2: nums1[start_replace_index] = num start_replace_index += 1 nums1.sort() ``` ```python= 2. Time = O(M+N), Space (1) class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ # Set p1 and p2 to point to the end of their respective arrays. p1 = m - 1 p2 = n - 1 # And move p backwards through the array, each time writing # the smallest value pointed at by p1 or p2. for p in range(n + m - 1, -1, -1): if p2 < 0: break if p1 >= 0 and nums1[p1] > nums2[p2]: nums1[p] = nums1[p1] p1 -= 1 else: nums1[p] = nums2[p2] p2 -= 1 ```