Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
weiy committed Jul 22, 2018
0 parents commit d74d7d7
Show file tree
Hide file tree
Showing 14 changed files with 815 additions and 0 deletions.
42 changes: 42 additions & 0 deletions Array/MergerTwoSortedList.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""
合并两个排序过的数组。
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
基本就是你走一步我走一步,一人一个指向。
O(n)
测试用例:
https://leetcode.com/problems/merge-two-sorted-lists/description/
"""

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):

def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""

head = cur = ListNode(0)

while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next

cur = cur.next

cur.next = l1 or l2

return head.next
51 changes: 51 additions & 0 deletions Array/max_increase_to_keep_city_skyline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""
Example:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation:
The grid is:
[ [3, 0, 8, 4],
[2, 4, 5, 7],
[9, 2, 6, 3],
[0, 3, 1, 0] ]
The skyline viewed from top or bottom is: [9, 4, 8, 7]
The skyline viewed from left or right is: [8, 7, 9, 3]
The grid after increasing the height of buildings without affecting skylines is:
gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]
测试用例:
https://leetcode.com/problems/max-increase-to-keep-city-skyline/description/
整体思路:
获取出x和y轴的最大值,然后逐个遍历。
时间复杂度 O(mn)。
"""

class Solution(object):
def maxIncreaseKeepingSkyline(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
length = len(grid[0])

# Get line max.
line_dict = {str(index):max(data) for index, data in enumerate(grid)}
# Get column max.
column_dict = {str(index):max((grid[index2][index] for index2 in range(len(grid)))) for index in range(length)}

total_increases = 0

for index, line in enumerate(grid):
for index2, cell in enumerate(line):
total_increases += min([line_dict[str(index)], column_dict[str(index2)]]) - cell

return total_increases
71 changes: 71 additions & 0 deletions Array/two_sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
数组中两个数相加,得到目标。
排序后的数组查找最快的就是二分法了。
基本思路:
排序,
二分查找。
用目标逐个相减然后查找是否存在(其实可以顺便返回位置,这样就不用index了。)。
所以时间复杂度 O(nlogn)
改进:
有O(n) 方式。
测试数据:
https://leetcode.com/problems/two-sum/description/
"""

class Solution(object):
def binarySearch(self, rawList, target):
split = len(rawList) // 2

left = rawList[:split]
right = rawList[split:]


if not left and not right:
return None

if left and left[-1] == target:
return True

if right and right[0] == target:
return True

if len(left) > 1 and left[-1] > target:
return self.binarySearch(left, target)

if len(right) > 1 and right[0] < target:
return self.binarySearch(right, target)


def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""

sortedNums = sorted(nums)
for i, data in enumerate(sortedNums):

# if data <= target:

if self.binarySearch(sortedNums[:i]+sortedNums[i+1:], target-data):
result = sorted([nums.index(data), nums.index(target-data)])
if result[0] == result[1]:
return [result[0], nums[result[0]+1:].index(target-data)+result[0]+1]

return result
# elif target < 0 and data > target:
# if self.binarySearch(nums[:i]+nums[i+1:], target-data):
# return sorted([i, nums[i+1:].index(target-data)+i+1])

55 changes: 55 additions & 0 deletions DP/longesSubsequence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""
整体思路是使用 DP。
DP 的核心是找到子问题。
该问题的子问题当前从此点向前与哪些组合可以形成最长的子串。
但与初级的抛硬币不同(要判断的只有3个),判断的点为从此点向前的所有点(子问题)。
时间复杂度 O(n**2)。
测试用例:
https://leetcode.com/problems/longest-increasing-subsequence/description/
另:有一个 O(nlogn) 的算法,暂未研究。
"""

"""
牛刀小试,DP 抛硬币,1 3 5 最少凑11。
def coins(num):
coins_result = {'0': 0}
for i in range(1, num+1):
coins_5, coins_3, coins_1 = float('inf'), float('inf'), float('inf')
if i-5 >= 0:
coins_5 = coins_result[str(i-5)] + 1
if i-3 >= 0:
coins_3 = coins_result[str(i-3)] + 1
if i-1 >= 0:
coins_1 = coins_result[str(i-1)] + 1
coins_result[str(i)] = min([coins_5, coins_3, coins_1])
print(coins_result)
print(coins_result[str(num)])
# coins(100)
"""

class Solution(object):
def lengthOfLIS(self, strings):
"""
:type nums: List[int]
:rtype: int
"""
if not strings:
return 0
long_ss = []

for i in strings:
if not long_ss:
long_ss.append(([i], 1))
continue
maxs = max(long_ss, key=lambda x: x[0][-1] < i and x[1]+1)
if maxs[0][-1] >= i:
long_ss.append(([i], 1))
else:
long_ss.append((maxs[0]+[i], maxs[1]+1))

return max(long_ss, key=lambda x: x[1])[1]
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# 算法相关知识储备

来源 leetCode 和 其他算法书。

## 数组相关
## 字符串相关
## 排序相关
##
## 动态规划
##

##

141 changes: 141 additions & 0 deletions Sorted/sotred.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
# 各种排序。
import random

test_list = (
list(range(10)),
list(range(100)),
list(range(1000)),
list(range(10001)),
list(range(50000))
)

list(map(random.shuffle, test_list))

result = (
list(range(10)),
list(range(100)),
list(range(1000)),
list(range(10001)),
list(range(50000))
)

# 选择排序:
# 每次选取一个最小的值。


def selectionSort(shuffledList):

new = []
for i in range(len(shuffledList)):
currentMinValue = min(shuffledList)
new.append(currentMinValue)
shuffledList.remove(currentMinValue)

return new

# 插入排序。
# 例:
# 插入排序一次只换一格。
# 4, 2, 3, 5, 9, 6, 1
# 2, 4, 3, 5, 9, 6, 1

# def insertingSort(shuffledList):

# new = shuffledList.copy()

# length = len(new)

# for i in range(1, length):
# if new[i] < new[i-1]:
# new[i], new[i-1] = new[i-1], new[i]

# return new
# def insertingSort(lst):
# for i in range(1,len(lst)):
# j = 0
# while lst[i] > lst[j]:
# j += 1
# results = lst[i]
# lst.pop(i)
# lst.insert(j,results)
# return lst

# 归并排序
# 归并排序是将一个大问题分解成多个小问题来解决。
# 归并排序包含两个步骤,其一是分解,其二是合并。
# 在排序中分解的过程就是将一整个数组分解为多个小数组。
# 合并则是两两合并,每次都分别从一个数组中提取一个进行比较,将较小的放入新的数组中。


def combined(list1, list2):
new = []
indexOne = 0
indexTwo = 0
lengthOne, lengthTwo = len(list1), len(list2)
while indexOne < lengthOne and indexTwo < lengthTwo:
valueOne = list1[indexOne]
valueTwo = list2[indexTwo]

if valueOne > valueTwo:
new.append(valueTwo)
indexTwo += 1
else:
new.append(valueOne)
indexOne +=1

if indexOne == lengthOne:
new.extend(list2[indexTwo:])
return new

if indexTwo == lengthTwo:
new.extend(list1[indexOne:])
return new


def makeValueInList(value):
return [value]


def reduce(splitedList):
length = len(splitedList)
if length == 1:
return splitedList[0]

middle = length // 2
left = reduce(splitedList[:middle])
right = reduce(splitedList[middle:])

return combined(left, right)


def mergeSort(shuffledList):

splitedList = list(map(makeValueInList, shuffledList))

result = reduce(splitedList)

return result


# 快速排序
# 快速排序的思路与归并排序一样都是基于分治,将一个大问题变成小问题再组合起来。
# 快排的平均时间消耗是O(logn), 当然最差也有n²。
# 快排的思路是,选取一个元素,将大于它的放在左边,小于的放在右边。然后将左边右边再次进行相同的操作。

def fastSort(shuffledList):
if len(shuffledList) <= 1:
return shuffledList

right = [i for i in shuffledList[1:] if i < shuffledList[0]]
left = [i for i in shuffledList[1:] if i >= shuffledList[0]]

return fastSort(right) + [shuffledList[0]] + fastSort(left)


for i, j in zip(test_list, result):
assert fastSort(i) == j
# assert mergeSort(i) == j
# break
# assert insertingSort(i) == j
# assert selectionSort(i) == j
# assert sorted(i) == j
Loading

0 comments on commit d74d7d7

Please sign in to comment.