update
No files matched your search
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 22 KiB |
@@ -0,0 +1,61 @@
|
||||
# Algorithm Homework 1
|
||||
> 姓名:阙建明
|
||||
>
|
||||
> 学号:1901213139
|
||||
|
||||
- ## 作业要求
|
||||
3道上课讲的LeetCode题目1,69,70
|
||||
|
||||
- ## Leetcode problem 1 (两数之和)
|
||||
- 算法思路:<br/>
|
||||
用字典记录数字,以便在找到成对的另一个数的时候,可以快速的检索到前一个数的索引
|
||||
|
||||
- Leetcode提交结果
|
||||

|
||||
- 代码:
|
||||
```python
|
||||
def twoSum(self, nums: List[int], target: int) -> List[int]:
|
||||
myDict = {}
|
||||
for index, num in enumerate(nums):
|
||||
if num in myDict:
|
||||
return [myDict[num], index]
|
||||
else:
|
||||
myDict[target - num] = index
|
||||
```
|
||||
|
||||
- ## Leetcode problem 69 (x 的平方根)
|
||||
- 算法思路:二分法
|
||||
|
||||
- Leetcode提交结果
|
||||

|
||||
- 代码:
|
||||
```python
|
||||
def mySqrt(self, x: int) -> int:
|
||||
if x in [1, 2, 3]:
|
||||
return 1
|
||||
left = 0
|
||||
right = x // 2
|
||||
while True:
|
||||
mid = (left + right) // 2
|
||||
if left + 1 >= right:
|
||||
break
|
||||
if mid < x / mid: # mid to small
|
||||
left = mid
|
||||
else:
|
||||
right = mid
|
||||
return right if right * right <= x else left
|
||||
```
|
||||
|
||||
- ## Leetcode problem 70 (爬楼梯)
|
||||
- 算法思路:动态规划。由于当前状态只取决于前两个状态,所以dp table可以精简为只用两个数表示
|
||||
|
||||
- Leetcode提交结果
|
||||

|
||||
- 代码:
|
||||
```python
|
||||
def climbStairs(self, n: int) -> int:
|
||||
pre, cur = 0, 1
|
||||
for i in range(1, n + 1):
|
||||
pre, cur = cur, pre + cur
|
||||
return cur
|
||||
```
|
||||
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 20 KiB |
@@ -0,0 +1,111 @@
|
||||
# Algorithm Homework 2
|
||||
|
||||
> 姓名:阙建明
|
||||
>
|
||||
> 学号:1901213139
|
||||
|
||||
## 作业要求:
|
||||
|
||||

|
||||
|
||||
## 题解
|
||||
|
||||
- ### Leetcode problem 7([整数反转](https://leetcode-cn.com/problems/reverse-integer/))
|
||||
|
||||
- **算法思路:**
|
||||
|
||||
- 首先记录是否为负数,接着将输入值取整
|
||||
- 用模10取余的方式依次得到反转的每一位,然后拼接到一个 *result* 当中
|
||||
- 最后判断是否溢出,溢出则返回0,不溢出则返回 *result* 或 *-result*
|
||||
|
||||
- **Leetcode提交结果:**
|
||||
|
||||

|
||||
|
||||
- **代码:**
|
||||
|
||||
```python
|
||||
INT_MAX_VAL = 2147483647
|
||||
INT_MIN_VAL = -2147483648
|
||||
class Solution:
|
||||
def reverse(self, x: int) -> int:
|
||||
isNegitive = -1 if x < 0 else 1
|
||||
result, x = 0, abs(x)
|
||||
while x > 0:
|
||||
result = result * 10 + x % 10
|
||||
x //= 10
|
||||
return 0 if result > INT_MAX_VAL or result < INT_MIN_VAL else isNegitive * result
|
||||
```
|
||||
|
||||
- ### Leetcode problem 13([罗马数字转整数](https://leetcode-cn.com/problems/roman-to-integer/))
|
||||
|
||||
- **算法思路:**
|
||||
|
||||
- 首先对于 *M、D、L、V*,可直接返回对应代表的数值
|
||||
- 对于 *C、X、I*,则如果右边出现可与之搭配成9 × 10n 或者 4 × 10n(n = 0, 1, 2)的情况,返回负的对应数值,否则返回正的对应数值
|
||||
|
||||
- **Leetcode提交结果:**
|
||||
|
||||

|
||||
|
||||
- **代码:**
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
def romanToInt(self, s: str) -> int:
|
||||
result, length = 0, len(s)
|
||||
for i in range(0, length):
|
||||
if s[i] == 'M':
|
||||
result += 1000
|
||||
elif s[i] == 'D':
|
||||
result += 500
|
||||
elif s[i] == 'C':
|
||||
if i < length - 1 and (s[i + 1] == 'M' or s[i + 1] == 'D'):
|
||||
result -= 100
|
||||
else:
|
||||
result += 100
|
||||
elif s[i] == 'L':
|
||||
result += 50
|
||||
elif s[i] == 'X':
|
||||
if i < length - 1 and (s[i + 1] == 'L' or s[i + 1] == 'C'):
|
||||
result -= 10
|
||||
else:
|
||||
result += 10
|
||||
elif s[i] == 'V':
|
||||
result += 5
|
||||
elif s[i] == 'I':
|
||||
if i < length - 1 and (s[i + 1] == 'V' or s[i + 1] == 'X'):
|
||||
result -= 1
|
||||
else:
|
||||
result += 1
|
||||
return result
|
||||
```
|
||||
|
||||
- ### Leetcode problem 3([加一](https://leetcode-cn.com/problems/plus-one/))
|
||||
|
||||
- **算法思路:**
|
||||
|
||||
- 从后往前遍历,每次 + 1,如果和等于10,则发生进位,否则算法返回
|
||||
- 遍历结束发现 *tmp* 仍然不为0,则表示数组的值为全9,需要在数组前添加一个元素
|
||||
|
||||
- **Leetcode提交结果:**
|
||||
|
||||

|
||||
|
||||
- **代码:**
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
def plusOne(self, digits: List[int]) -> List[int]:
|
||||
tmp = digits[len(digits) - 1] + 1
|
||||
digits[len(digits) - 1], tmp, index = tmp % 10, tmp // 10, len(digits) - 2
|
||||
while tmp != 0 and index >= 0:
|
||||
tmp = digits[index] + 1
|
||||
digits[index], tmp = tmp % 10, tmp // 10
|
||||
index -= 1
|
||||
if tmp != 0:
|
||||
digits.insert(0, 1)
|
||||
return digits
|
||||
```
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 20 KiB |
@@ -0,0 +1,111 @@
|
||||
# Algorithm Homework 3
|
||||
|
||||
> 姓名:阙建明
|
||||
>
|
||||
> 学号:1901213139
|
||||
|
||||
## 作业要求:
|
||||
|
||||
Leetcode: 35,58,83
|
||||
|
||||
## 题解:
|
||||
|
||||
- ### Leetcode problem 35([搜索插入位置](https://leetcode-cn.com/problems/search-insert-position/))
|
||||
|
||||
- **算法思路:**
|
||||
|
||||
- 尝试使用二分法找到target的索引,找到则返回
|
||||
- 没有找到则判断target与左右索引的大小关系,返回应该插入的位置
|
||||
|
||||
- **Leetcode提交结果:**
|
||||
|
||||

|
||||
|
||||
- **代码:**
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
def searchInsert(self, nums: List[int], target: int) -> int:
|
||||
left, right = 0, len(nums) - 1
|
||||
while left < right - 1:
|
||||
pos = (left + right) // 2
|
||||
if nums[pos] > target:
|
||||
right = pos
|
||||
elif nums[pos] < target:
|
||||
left = pos
|
||||
else:
|
||||
return pos
|
||||
if nums[left] == target or target < nums[left]:
|
||||
return left
|
||||
elif nums[right] == target or target < nums[right]:
|
||||
return right
|
||||
else:
|
||||
return right + 1
|
||||
```
|
||||
|
||||
- ### Leetcode problem 58([最后一个单词的长度](https://leetcode-cn.com/problems/length-of-last-word/))
|
||||
|
||||
- **算法思路:**
|
||||
|
||||
- 思路1:使用`split`将字符串用空格分割成数组,然后反序遍历,取第一个非空字符串的长度,无则返回0;
|
||||
- 思路2:使用`strip`截掉字符串前后的空格,然后反序遍历统计最后一个单次的长度,无则返回0。
|
||||
|
||||
- **Leetcode提交结果:**
|
||||
|
||||

|
||||
|
||||
- **代码:**
|
||||
|
||||
```python
|
||||
# 思路1代码
|
||||
class Solution:
|
||||
def lengthOfLastWord(self, s: str) -> int:
|
||||
strs = s.split(' ')
|
||||
for i in range(0, len(strs))[::-1]:
|
||||
if len(strs[i]) > 0: return len(strs[i])
|
||||
return 0
|
||||
|
||||
# 思路2代码(性能更优)
|
||||
class Solution:
|
||||
def lengthOfLastWord(self, s: str) -> int:
|
||||
s = s.strip()
|
||||
count = 0
|
||||
for i in range(0, len(s))[::-1]:
|
||||
if s[i] == ' ':
|
||||
return count
|
||||
else:
|
||||
count += 1
|
||||
return count
|
||||
```
|
||||
|
||||
- ### Leetcode problem 83([删除排序链表中的重复元素](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/))
|
||||
|
||||
- **算法思路:**
|
||||
|
||||
- 用一个set记录当前遍历过的值
|
||||
- 遍历到每一个节点,用set检查当前值是否存在于set,如果存在则删除该节点
|
||||
|
||||
- **Leetcode提交结果:**
|
||||
|
||||

|
||||
|
||||
- **代码:**
|
||||
|
||||
```python
|
||||
class Solution:
|
||||
def deleteDuplicates(self, head: ListNode) -> ListNode:
|
||||
if head == None:
|
||||
return head
|
||||
s, pre, cur = set(), head, head.next
|
||||
s.add(pre.val)
|
||||
while cur is not None:
|
||||
if cur.val in s:
|
||||
pre.next, cur = cur.next, cur.next
|
||||
continue
|
||||
else:
|
||||
s.add(cur.val)
|
||||
pre, cur = cur, cur.next
|
||||
return head
|
||||
```
|
||||
|
||||
|
||||
@@ -1 +1,5 @@
|
||||
# algorithm-homework
|
||||
|
||||
- [第一次作业](AlgorithmHomework1.md)
|
||||
- [第二次作业](AlgorithmHomework2.md)
|
||||
- [第三次作业](AlgorithmHomework3.md)
|
||||
@@ -0,0 +1,103 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>算法课作业-阙建明</title>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
|
||||
<meta name="description" content="Description">
|
||||
<meta name="viewport"
|
||||
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
|
||||
<link rel="stylesheet" href="//unpkg.com/docsify/lib/themes/vue.css">
|
||||
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.css">
|
||||
<link href="//cdn.bootcss.com/prism/9000.0.1/themes/prism.min.css" rel="stylesheet">
|
||||
<link rel="stylesheet" href="//unpkg.com/gitalk/dist/gitalk.css">
|
||||
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/katex@latest/dist/katex.min.css"/>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script src="//cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
|
||||
<script src="//cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
|
||||
<script src="//unpkg.com/docsify/lib/docsify.min.js"></script>
|
||||
<script>
|
||||
function NewGitalk() {
|
||||
let id = decodeURI(`${window.location.hash}`);
|
||||
console.log(`id: ${id}`);
|
||||
console.log(window.location);
|
||||
const title = `Gitalk评论${decodeURI(window.location.pathname)}${window.location.hash}`;
|
||||
if (id.length > 50) {
|
||||
id = id.substr(0, 50);
|
||||
}
|
||||
return new Gitalk({
|
||||
title: title,
|
||||
clientID: 'fa290550335fbd43a74e',
|
||||
clientSecret: '4c7ba77a9bb7f1f0694f29af4d18c00479bba5c6',
|
||||
repo: 'nfd-developer-guide-zh',
|
||||
owner: 'SunnyQjm',
|
||||
admin: ['SunnyQjm'],
|
||||
// facebook-like distraction free mode
|
||||
distractionFreeMode: false
|
||||
})
|
||||
}
|
||||
</script>
|
||||
<script>
|
||||
var num = 0;
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
flowchart: {
|
||||
useMaxWidth: true,
|
||||
htmlLabels: false,
|
||||
curve: 'cardinal',
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
window.$docsify = {
|
||||
name: '算法课作业',
|
||||
repo: 'https://github.com/SunnyQjm/algorithm-homework',
|
||||
autoHeader: true,
|
||||
subMaxLevel: 4,
|
||||
auto2top: true,
|
||||
markdown: {
|
||||
renderer: {
|
||||
code: function (code, lang) {
|
||||
if (lang === "mermaid") {
|
||||
return (
|
||||
'<div class="mermaid">' + mermaid.render('mermaid-svg-' + num++, code) + "</div>"
|
||||
);
|
||||
}
|
||||
return this.origin.code.apply(this, arguments);
|
||||
}
|
||||
}
|
||||
},
|
||||
plugins: [
|
||||
function(hook, vm) {
|
||||
hook.doneEach(function(){
|
||||
//const elem = document.getElementById('gitalk-container');
|
||||
//elem && (elem.innerHTML = "");
|
||||
//NewGitalk().render('gitalk-container');
|
||||
});
|
||||
}
|
||||
]
|
||||
};
|
||||
$(document).ready(function () {
|
||||
$('pre').addClass("line-numbers").css("white-space", "pre-wrap");
|
||||
})
|
||||
NewGitalk()
|
||||
</script>
|
||||
<script src="//unpkg.com/docsify-copy-code"></script>
|
||||
<script src="//unpkg.com/prismjs/components/prism-bash.min.js"></script>
|
||||
<script src="//unpkg.com/prismjs/components/prism-c.min.js"></script>
|
||||
<script src="//unpkg.com/prismjs/components/prism-cpp.min.js"></script>
|
||||
<script src="//unpkg.com/prismjs/components/prism-python.min.js"></script>
|
||||
<script src="//unpkg.com/docsify/lib/plugins/zoom-image.min.js"></script>
|
||||
<!-- CDN files for docsify-katex -->
|
||||
<script src="//cdn.jsdelivr.net/npm/docsify-katex@latest/dist/docsify-katex.js"></script>
|
||||
<!-- Gitalk 配置 -->
|
||||
<script src="//unpkg.com/docsify/lib/plugins/gitalk.js"></script>
|
||||
<script src="//unpkg.com/gitalk/dist/gitalk.min.js"></script>
|
||||
<script>
|
||||
const gitalk = NewGitalk()
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||