Before we learn algorithm, It is better scan following five types one by one.
- array
- string
- tree
- linkedlist
- math
These five kinds of algorithms help you establish algorithm thinking which is essential to solve problems. You can also know engouth about data structure. Let’s go to the first one.
Array - Easy
2. Two-Sum
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
# two point, to record the original index of the array
nums_index = [(v, index) for index, v in enumerate(nums)]
nums_index.sort()
begin, end = 0, len(nums) - 1
while begin < end:
curr = nums_index[begin][0] + nums_index[end][0]
if curr == target:
return [nums_index[begin][1], nums_index[end][1]]
elif curr < target:
begin += 1
else:
end -= 1
########################## Method 2 #############################
"""
this is a dynamic programming concept called Memoization, It's the main concept of this question in order to solve it efficiently, essentially n is the complement of num (target sum - num), since we want the indices of two numbers that add to target, the index of the complement of any given num is what we want to find, so if we don't find it, we store it in a hash map so we can look it later.
since hashmaps have constant time look up, it is efficient.
nums=[2,7,11,15,17,18,21,22,42,56]
target = 35
# final stage
h = {2: 0, 7: 1, 11: 2, 15: 3, 17: 4}
n=17
17 not in h == false
h[17]==4, i== 5
"""
h = {}
for i, num in enumerate(nums):
n = target - num
if n not in h: # h[n]?
h[num] = i
else:
return [h[n], i]
tip: python emuerate allows us to loop over something and have an automatic counter. Here is an example:
my_list = ['apple', 'banana', 'grapes', 'pear']
for c, value in enumerate(my_list, 1):
print(c, value)
# Output:
# 1 apple
# 2 banana
# 3 grapes
# 4 pear
Here I have a idea in sudden, If the intergers are positive ones, we can use binary search to find the position of a number near to target. Then we can set result to the ‘end’.
def binarySearch(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
begin, end = 0, len(nums)
while end > begin+1:
position = int(math.ceil((begin + end)/2))
num = nums[position]
if(num == target):
return num
elif num < target:
begin = position
else:
end = position
return end
26. remove-duplicates-from-sorted-array
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
left = 0 # used to record the position of first non-dumplicate number
for i in range(1, len(nums)):
if nums[left] == nums[i]:
continue
else:
left += 1
nums[left] = nums[i]
return left + 1
27. remove-element
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
left = 0
for i in range(len(nums)):
if nums[i] == val:
continue
else:
# normal loop implement
nums[left] = nums[i]
left += 1
return left
35. search-insert-position
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
begin, end=0, len(nums)-1
if nums[end] < target:
return end+1
if nums[begin] > target:
return begin
while begin < end:
pos = int((begin+end)/2)
if nums[pos] == target:
return pos
elif nums[pos] > target:
end = pos
else:
begin = pos + 1
return begin
#################### Method 2 ##################################
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
l, r = 0, len(nums) - 1
while l < r:
mid = (l + r) / 2
if nums[mid] < target:
l = mid + 1
else:
r = mid
if nums[l] < target: #consider the largest value in the end of array
return l + 1
return l