mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge branch 'master' of github.com:youngyangyang04/leetcode-master
This commit is contained in:
@ -206,6 +206,48 @@ function twoSum(array $nums, int $target): array
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Swift:
|
||||||
|
```swift
|
||||||
|
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
|
||||||
|
var res = [Int]()
|
||||||
|
var dict = [Int : Int]()
|
||||||
|
for i in 0 ..< nums.count {
|
||||||
|
let other = target - nums[i]
|
||||||
|
if dict.keys.contains(other) {
|
||||||
|
res.append(i)
|
||||||
|
res.append(dict[other]!)
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
dict[nums[i]] = i
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
PHP:
|
||||||
|
```php
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* @param Integer[] $nums
|
||||||
|
* @param Integer $target
|
||||||
|
* @return Integer[]
|
||||||
|
*/
|
||||||
|
function twoSum($nums, $target) {
|
||||||
|
if (count($nums) == 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
$table = [];
|
||||||
|
for ($i = 0; $i < count($nums); $i++) {
|
||||||
|
$temp = $target - $nums[$i];
|
||||||
|
if (isset($table[$temp])) {
|
||||||
|
return [$table[$temp], $i];
|
||||||
|
}
|
||||||
|
$table[$nums[$i]] = $i;
|
||||||
|
}
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
@ -393,6 +393,46 @@ function threeSum(array $nums): array
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
PHP:
|
||||||
|
```php
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* @param Integer[] $nums
|
||||||
|
* @return Integer[][]
|
||||||
|
*/
|
||||||
|
function threeSum($nums) {
|
||||||
|
$res = [];
|
||||||
|
sort($nums);
|
||||||
|
for ($i = 0; $i < count($nums); $i++) {
|
||||||
|
if ($nums[$i] > 0) {
|
||||||
|
return $res;
|
||||||
|
}
|
||||||
|
if ($i > 0 && $nums[$i] == $nums[$i - 1]) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$left = $i + 1;
|
||||||
|
$right = count($nums) - 1;
|
||||||
|
while ($left < $right) {
|
||||||
|
$sum = $nums[$i] + $nums[$left] + $nums[$right];
|
||||||
|
if ($sum < 0) {
|
||||||
|
$left++;
|
||||||
|
}
|
||||||
|
else if ($sum > 0) {
|
||||||
|
$right--;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
$res[] = [$nums[$i], $nums[$left], $nums[$right]];
|
||||||
|
while ($left < $right && $nums[$left] == $nums[$left + 1]) $left++;
|
||||||
|
while ($left < $right && $nums[$right] == $nums[$right - 1]) $right--;
|
||||||
|
$left++;
|
||||||
|
$right--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
@ -322,20 +322,20 @@ python3:
|
|||||||
```py
|
```py
|
||||||
class Solution:
|
class Solution:
|
||||||
def letterCombinations(self, digits: str) -> List[str]:
|
def letterCombinations(self, digits: str) -> List[str]:
|
||||||
self.s = ""
|
|
||||||
res = []
|
res = []
|
||||||
|
s = ""
|
||||||
letterMap = ["","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
|
letterMap = ["","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
|
||||||
if len(digits) == 0: return res
|
if not len(digits): return res
|
||||||
def backtrack(digits,index):
|
def backtrack(digits,index, s):
|
||||||
if index == len(digits):
|
if index == len(digits):
|
||||||
return res.append(self.s)
|
return res.append(s)
|
||||||
digit = int(digits[index]) #将index指向的数字转为int
|
digit = int(digits[index]) #将index指向的数字转为int
|
||||||
letters = letterMap[digit] #取数字对应的字符集
|
letters = letterMap[digit] #取数字对应的字符集
|
||||||
for i in range(len(letters)):
|
for i in range(len(letters)):
|
||||||
self.s += letters[i]
|
s += letters[i]
|
||||||
backtrack(digits,index + 1) #递归,注意index+1,一下层要处理下一个数字
|
backtrack(digits, index+1, s) #递归,注意index+1,一下层要处理下一个数字
|
||||||
self.s = self.s[:-1] #回溯
|
s = s[:-1] #回溯
|
||||||
backtrack(digits,0)
|
backtrack(digits, 0, s)
|
||||||
return res
|
return res
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -310,6 +310,49 @@ var fourSum = function(nums, target) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
PHP:
|
||||||
|
```php
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* @param Integer[] $nums
|
||||||
|
* @param Integer $target
|
||||||
|
* @return Integer[][]
|
||||||
|
*/
|
||||||
|
function fourSum($nums, $target) {
|
||||||
|
$res = [];
|
||||||
|
sort($nums);
|
||||||
|
for ($i = 0; $i < count($nums); $i++) {
|
||||||
|
if ($i > 0 && $nums[$i] == $nums[$i - 1]) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for ($j = $i + 1; $j < count($nums); $j++) {
|
||||||
|
if ($j > $i + 1 && $nums[$j] == $nums[$j - 1]) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
$left = $j + 1;
|
||||||
|
$right = count($nums) - 1;
|
||||||
|
while ($left < $right) {
|
||||||
|
$sum = $nums[$i] + $nums[$j] + $nums[$left] + $nums[$right];
|
||||||
|
if ($sum < $target) {
|
||||||
|
$left++;
|
||||||
|
}
|
||||||
|
else if ($sum > $target) {
|
||||||
|
$right--;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
$res[] = [$nums[$i], $nums[$j], $nums[$left], $nums[$right]];
|
||||||
|
while ($left < $right && $nums[$left] == $nums[$left+1]) $left++;
|
||||||
|
while ($left < $right && $nums[$right] == $nums[$right-1]) $right--;
|
||||||
|
$left++;
|
||||||
|
$right--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
@ -246,6 +246,46 @@ func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
PHP:
|
||||||
|
```php
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* @param Integer[] $nums
|
||||||
|
* @param Integer $val
|
||||||
|
* @return Integer
|
||||||
|
*/
|
||||||
|
function removeElement(&$nums, $val) {
|
||||||
|
if (count($nums) == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
// 快慢指针
|
||||||
|
$slow = 0;
|
||||||
|
for ($fast = 0; $fast < count($nums); $fast++) {
|
||||||
|
if ($nums[$fast] != $val) {
|
||||||
|
$nums[$slow] = $nums[$fast];
|
||||||
|
$slow++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $slow;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
C:
|
||||||
|
```c
|
||||||
|
int removeElement(int* nums, int numsSize, int val){
|
||||||
|
int slow = 0;
|
||||||
|
for(int fast = 0; fast < numsSize; fast++) {
|
||||||
|
//若快指针位置的元素不等于要删除的元素
|
||||||
|
if(nums[fast] != val) {
|
||||||
|
//将其挪到慢指针指向的位置,慢指针+1
|
||||||
|
nums[slow++] = nums[fast];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//最后慢指针的大小就是新的数组的大小
|
||||||
|
return slow;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||||
|
@ -183,6 +183,32 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
```java
|
||||||
|
// 解法2:通过判断path中是否存在数字,排除已经选择的数字
|
||||||
|
class Solution {
|
||||||
|
List<List<Integer>> result = new ArrayList<>();
|
||||||
|
LinkedList<Integer> path = new LinkedList<>();
|
||||||
|
public List<List<Integer>> permute(int[] nums) {
|
||||||
|
if (nums.length == 0) return result;
|
||||||
|
backtrack(nums, path);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
public void backtrack(int[] nums, LinkedList<Integer> path) {
|
||||||
|
if (path.size() == nums.length) {
|
||||||
|
result.add(new ArrayList<>(path));
|
||||||
|
}
|
||||||
|
for (int i =0; i < nums.length; i++) {
|
||||||
|
// 如果path中已有,则跳过
|
||||||
|
if (path.contains(nums[i])) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
path.add(nums[i]);
|
||||||
|
backtrack(nums, path);
|
||||||
|
path.removeLast();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
```python3
|
```python3
|
||||||
|
@ -157,6 +157,28 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
```java
|
||||||
|
// 版本2
|
||||||
|
class Solution {
|
||||||
|
public int[][] merge(int[][] intervals) {
|
||||||
|
LinkedList<int[]> res = new LinkedList<>();
|
||||||
|
Arrays.sort(intervals, (o1, o2) -> Integer.compare(o1[0], o2[0]));
|
||||||
|
res.add(intervals[0]);
|
||||||
|
for (int i = 1; i < intervals.length; i++) {
|
||||||
|
if (intervals[i][0] <= res.getLast()[1]) {
|
||||||
|
int start = res.getLast()[0];
|
||||||
|
int end = Math.max(intervals[i][1], res.getLast()[1]);
|
||||||
|
res.removeLast();
|
||||||
|
res.add(new int[]{start, end});
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
res.add(intervals[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res.toArray(new int[res.size()][]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
```python
|
```python
|
||||||
|
@ -426,6 +426,48 @@ impl Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
PHP:
|
||||||
|
```php
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* @param Integer $n
|
||||||
|
* @return Integer[][]
|
||||||
|
*/
|
||||||
|
function generateMatrix($n) {
|
||||||
|
// 初始化数组
|
||||||
|
$res = array_fill(0, $n, array_fill(0, $n, 0));
|
||||||
|
$mid = $loop = floor($n / 2);
|
||||||
|
$startX = $startY = 0;
|
||||||
|
$offset = 1;
|
||||||
|
$count = 1;
|
||||||
|
while ($loop > 0) {
|
||||||
|
$i = $startX;
|
||||||
|
$j = $startY;
|
||||||
|
for (; $j < $startY + $n - $offset; $j++) {
|
||||||
|
$res[$i][$j] = $count++;
|
||||||
|
}
|
||||||
|
for (; $i < $startX + $n - $offset; $i++) {
|
||||||
|
$res[$i][$j] = $count++;
|
||||||
|
}
|
||||||
|
for (; $j > $startY; $j--) {
|
||||||
|
$res[$i][$j] = $count++;
|
||||||
|
}
|
||||||
|
for (; $i > $startX; $i--) {
|
||||||
|
$res[$i][$j] = $count++;
|
||||||
|
}
|
||||||
|
$startX += 1;
|
||||||
|
$startY += 1;
|
||||||
|
$offset += 2;
|
||||||
|
$loop--;
|
||||||
|
}
|
||||||
|
if ($n % 2 == 1) {
|
||||||
|
$res[$mid][$mid] = $count;
|
||||||
|
}
|
||||||
|
return $res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
@ -435,6 +435,59 @@ func backtrack(n,k,start int,track []int){
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
C:
|
||||||
|
```c
|
||||||
|
int* path;
|
||||||
|
int pathTop;
|
||||||
|
int** ans;
|
||||||
|
int ansTop;
|
||||||
|
|
||||||
|
void backtracking(int n, int k,int startIndex) {
|
||||||
|
//当path中元素个数为k个时,我们需要将path数组放入ans二维数组中
|
||||||
|
if(pathTop == k) {
|
||||||
|
//path数组为我们动态申请,若直接将其地址放入二维数组,path数组中的值会随着我们回溯而逐渐变化
|
||||||
|
//因此创建新的数组存储path中的值
|
||||||
|
int* temp = (int*)malloc(sizeof(int) * k);
|
||||||
|
int i;
|
||||||
|
for(i = 0; i < k; i++) {
|
||||||
|
temp[i] = path[i];
|
||||||
|
}
|
||||||
|
ans[ansTop++] = temp;
|
||||||
|
return ;
|
||||||
|
}
|
||||||
|
|
||||||
|
int j;
|
||||||
|
for(j = startIndex; j <=n ;j++) {
|
||||||
|
//将当前结点放入path数组
|
||||||
|
path[pathTop++] = j;
|
||||||
|
//进行递归
|
||||||
|
backtracking(n, k, j + 1);
|
||||||
|
//进行回溯,将数组最上层结点弹出
|
||||||
|
pathTop--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int** combine(int n, int k, int* returnSize, int** returnColumnSizes){
|
||||||
|
//path数组存储符合条件的结果
|
||||||
|
path = (int*)malloc(sizeof(int) * k);
|
||||||
|
//ans二维数组存储符合条件的结果数组的集合。(数组足够大,避免极端情况)
|
||||||
|
ans = (int**)malloc(sizeof(int*) * 10000);
|
||||||
|
pathTop = ansTop = 0;
|
||||||
|
|
||||||
|
//回溯算法
|
||||||
|
backtracking(n, k, 1);
|
||||||
|
//最后的返回大小为ans数组大小
|
||||||
|
*returnSize = ansTop;
|
||||||
|
//returnColumnSizes数组存储ans二维数组对应下标中一维数组的长度(都为k)
|
||||||
|
*returnColumnSizes = (int*)malloc(sizeof(int) *(*returnSize));
|
||||||
|
int i;
|
||||||
|
for(i = 0; i < *returnSize; i++) {
|
||||||
|
(*returnColumnSizes)[i] = k;
|
||||||
|
}
|
||||||
|
//返回ans二维数组
|
||||||
|
return ans;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
@ -242,8 +242,59 @@ var combine = function(n, k) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
C:
|
||||||
|
```c
|
||||||
|
int* path;
|
||||||
|
int pathTop;
|
||||||
|
int** ans;
|
||||||
|
int ansTop;
|
||||||
|
|
||||||
|
void backtracking(int n, int k,int startIndex) {
|
||||||
|
//当path中元素个数为k个时,我们需要将path数组放入ans二维数组中
|
||||||
|
if(pathTop == k) {
|
||||||
|
//path数组为我们动态申请,若直接将其地址放入二维数组,path数组中的值会随着我们回溯而逐渐变化
|
||||||
|
//因此创建新的数组存储path中的值
|
||||||
|
int* temp = (int*)malloc(sizeof(int) * k);
|
||||||
|
int i;
|
||||||
|
for(i = 0; i < k; i++) {
|
||||||
|
temp[i] = path[i];
|
||||||
|
}
|
||||||
|
ans[ansTop++] = temp;
|
||||||
|
return ;
|
||||||
|
}
|
||||||
|
|
||||||
|
int j;
|
||||||
|
for(j = startIndex; j <= n- (k - pathTop) + 1;j++) {
|
||||||
|
//将当前结点放入path数组
|
||||||
|
path[pathTop++] = j;
|
||||||
|
//进行递归
|
||||||
|
backtracking(n, k, j + 1);
|
||||||
|
//进行回溯,将数组最上层结点弹出
|
||||||
|
pathTop--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int** combine(int n, int k, int* returnSize, int** returnColumnSizes){
|
||||||
|
//path数组存储符合条件的结果
|
||||||
|
path = (int*)malloc(sizeof(int) * k);
|
||||||
|
//ans二维数组存储符合条件的结果数组的集合。(数组足够大,避免极端情况)
|
||||||
|
ans = (int**)malloc(sizeof(int*) * 10000);
|
||||||
|
pathTop = ansTop = 0;
|
||||||
|
|
||||||
|
//回溯算法
|
||||||
|
backtracking(n, k, 1);
|
||||||
|
//最后的返回大小为ans数组大小
|
||||||
|
*returnSize = ansTop;
|
||||||
|
//returnColumnSizes数组存储ans二维数组对应下标中一维数组的长度(都为k)
|
||||||
|
*returnColumnSizes = (int*)malloc(sizeof(int) *(*returnSize));
|
||||||
|
int i;
|
||||||
|
for(i = 0; i < *returnSize; i++) {
|
||||||
|
(*returnColumnSizes)[i] = k;
|
||||||
|
}
|
||||||
|
//返回ans二维数组
|
||||||
|
return ans;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
@ -87,28 +87,48 @@ public:
|
|||||||
|
|
||||||
python代码:
|
python代码:
|
||||||
|
|
||||||
|
|
||||||
|
```python3
|
||||||
|
|
||||||
|
class Solution:
|
||||||
|
"""二叉树层序遍历迭代解法"""
|
||||||
|
|
||||||
|
def levelOrder(self, root: TreeNode) -> List[List[int]]:
|
||||||
|
results = []
|
||||||
|
if not root:
|
||||||
|
return results
|
||||||
|
|
||||||
|
from collections import deque
|
||||||
|
que = deque([root])
|
||||||
|
|
||||||
|
while que:
|
||||||
|
size = len(que)
|
||||||
|
result = []
|
||||||
|
for _ in range(size):
|
||||||
|
cur = que.popleft()
|
||||||
|
result.append(cur.val)
|
||||||
|
if cur.left:
|
||||||
|
que.append(cur.left)
|
||||||
|
if cur.right:
|
||||||
|
que.append(cur.right)
|
||||||
|
results.append(result)
|
||||||
|
|
||||||
|
return results
|
||||||
|
```
|
||||||
```python
|
```python
|
||||||
|
# 递归法
|
||||||
class Solution:
|
class Solution:
|
||||||
def levelOrder(self, root: TreeNode) -> List[List[int]]:
|
def levelOrder(self, root: TreeNode) -> List[List[int]]:
|
||||||
if not root:
|
res = []
|
||||||
return []
|
def helper(root, depth):
|
||||||
|
if not root: return []
|
||||||
queue = [root]
|
if len(res) == depth: res.append([]) # start the current depth
|
||||||
out_list = []
|
res[depth].append(root.val) # fulfil the current depth
|
||||||
|
if root.left: helper(root.left, depth + 1) # process child nodes for the next depth
|
||||||
while queue:
|
if root.right: helper(root.right, depth + 1)
|
||||||
length = len(queue)
|
helper(root, 0)
|
||||||
in_list = []
|
return res
|
||||||
for _ in range(length):
|
|
||||||
curnode = queue.pop(0) # (默认移除列表最后一个元素)这里需要移除队列最头上的那个
|
|
||||||
in_list.append(curnode.val)
|
|
||||||
if curnode.left: queue.append(curnode.left)
|
|
||||||
if curnode.right: queue.append(curnode.right)
|
|
||||||
out_list.append(in_list)
|
|
||||||
|
|
||||||
return out_list
|
|
||||||
```
|
```
|
||||||
|
|
||||||
java:
|
java:
|
||||||
|
|
||||||
```Java
|
```Java
|
||||||
@ -274,29 +294,29 @@ python代码:
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
|
"""二叉树层序遍历II迭代解法"""
|
||||||
|
|
||||||
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
|
def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
|
||||||
|
results = []
|
||||||
if not root:
|
if not root:
|
||||||
return []
|
return results
|
||||||
quene = [root]
|
|
||||||
out_list = []
|
|
||||||
|
|
||||||
while quene:
|
from collections import deque
|
||||||
in_list = []
|
que = deque([root])
|
||||||
for _ in range(len(quene)):
|
|
||||||
node = quene.pop(0)
|
while que:
|
||||||
in_list.append(node.val)
|
result = []
|
||||||
if node.left:
|
for _ in range(len(que)):
|
||||||
quene.append(node.left)
|
cur = que.popleft()
|
||||||
if node.right:
|
result.append(cur.val)
|
||||||
quene.append(node.right)
|
if cur.left:
|
||||||
|
que.append(cur.left)
|
||||||
out_list.append(in_list)
|
if cur.right:
|
||||||
|
que.append(cur.right)
|
||||||
out_list.reverse()
|
results.append(result)
|
||||||
return out_list
|
|
||||||
|
results.reverse()
|
||||||
# 执行用时:36 ms, 在所有 Python3 提交中击败了92.00%的用户
|
return results
|
||||||
# 内存消耗:15.2 MB, 在所有 Python3 提交中击败了63.76%的用户
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
@ -628,32 +648,29 @@ python代码:
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
|
"""二叉树层平均值迭代解法"""
|
||||||
|
|
||||||
def averageOfLevels(self, root: TreeNode) -> List[float]:
|
def averageOfLevels(self, root: TreeNode) -> List[float]:
|
||||||
|
results = []
|
||||||
if not root:
|
if not root:
|
||||||
return []
|
return results
|
||||||
|
|
||||||
quene = deque([root])
|
from collections import deque
|
||||||
out_list = []
|
que = deque([root])
|
||||||
|
|
||||||
while quene:
|
|
||||||
in_list = []
|
|
||||||
|
|
||||||
for _ in range(len(quene)):
|
|
||||||
node = quene.popleft()
|
|
||||||
in_list.append(node.val)
|
|
||||||
if node.left:
|
|
||||||
quene.append(node.left)
|
|
||||||
if node.right:
|
|
||||||
quene.append(node.right)
|
|
||||||
|
|
||||||
out_list.append(in_list)
|
|
||||||
|
|
||||||
out_list = map(lambda x: sum(x) / len(x), out_list)
|
|
||||||
|
|
||||||
return out_list
|
|
||||||
|
|
||||||
# 执行用时:56 ms, 在所有 Python3 提交中击败了81.48%的用户
|
while que:
|
||||||
# 内存消耗:17 MB, 在所有 Python3 提交中击败了89.68%的用户
|
size = len(que)
|
||||||
|
sum_ = 0
|
||||||
|
for _ in range(size):
|
||||||
|
cur = que.popleft()
|
||||||
|
sum_ += cur.val
|
||||||
|
if cur.left:
|
||||||
|
que.append(cur.left)
|
||||||
|
if cur.right:
|
||||||
|
que.append(cur.right)
|
||||||
|
results.append(sum_ / size)
|
||||||
|
|
||||||
|
return results
|
||||||
```
|
```
|
||||||
|
|
||||||
java:
|
java:
|
||||||
@ -823,52 +840,28 @@ public:
|
|||||||
python代码:
|
python代码:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
|
||||||
class Solution:
|
class Solution:
|
||||||
|
"""N叉树的层序遍历迭代法"""
|
||||||
|
|
||||||
def levelOrder(self, root: 'Node') -> List[List[int]]:
|
def levelOrder(self, root: 'Node') -> List[List[int]]:
|
||||||
|
results = []
|
||||||
if not root:
|
if not root:
|
||||||
return []
|
return results
|
||||||
|
|
||||||
quene = deque([root])
|
from collections import deque
|
||||||
out_list = []
|
que = deque([root])
|
||||||
|
|
||||||
while quene:
|
|
||||||
in_list = []
|
|
||||||
|
|
||||||
for _ in range(len(quene)):
|
|
||||||
node = quene.popleft()
|
|
||||||
in_list.append(node.val)
|
|
||||||
if node.children:
|
|
||||||
# 这个地方要用extend而不是append,我们看下面的例子:
|
|
||||||
# In [18]: alist=[]
|
|
||||||
# In [19]: alist.append([1,2,3])
|
|
||||||
# In [20]: alist
|
|
||||||
# Out[20]: [[1, 2, 3]]
|
|
||||||
# In [21]: alist.extend([4,5,6])
|
|
||||||
# In [22]: alist
|
|
||||||
# Out[22]: [[1, 2, 3], 4, 5, 6]
|
|
||||||
# 可以看到extend对要添加的list进行了一个解包操作
|
|
||||||
# print(root.children),可以得到children是一个包含
|
|
||||||
# 孩子节点地址的list,我们使用for遍历quene的时候,
|
|
||||||
# 希望quene是一个单层list,所以要用extend
|
|
||||||
# 使用extend的情况,如果print(quene),结果是
|
|
||||||
# deque([<__main__.Node object at 0x7f60763ae0a0>])
|
|
||||||
# deque([<__main__.Node object at 0x7f607636e6d0>, <__main__.Node object at 0x7f607636e130>, <__main__.Node object at 0x7f607636e310>])
|
|
||||||
# deque([<__main__.Node object at 0x7f607636e880>, <__main__.Node object at 0x7f607636ef10>])
|
|
||||||
# 可以看到是单层list
|
|
||||||
# 如果使用append,print(quene)的结果是
|
|
||||||
# deque([<__main__.Node object at 0x7f18907530a0>])
|
|
||||||
# deque([[<__main__.Node object at 0x7f18907136d0>, <__main__.Node object at 0x7f1890713130>, <__main__.Node object at 0x7f1890713310>]])
|
|
||||||
# 可以看到是两层list,这样for的遍历就会报错
|
|
||||||
|
|
||||||
quene.extend(node.children)
|
|
||||||
|
|
||||||
out_list.append(in_list)
|
|
||||||
|
|
||||||
return out_list
|
while que:
|
||||||
|
result = []
|
||||||
# 执行用时:60 ms, 在所有 Python3 提交中击败了76.99%的用户
|
for _ in range(len(que)):
|
||||||
# 内存消耗:16.5 MB, 在所有 Python3 提交中击败了89.19%的用户
|
cur = que.popleft()
|
||||||
|
result.append(cur.val)
|
||||||
|
# cur.children 是 Node 对象组成的列表,也可能为 None
|
||||||
|
if cur.children:
|
||||||
|
que.extend(cur.children)
|
||||||
|
results.append(result)
|
||||||
|
|
||||||
|
return results
|
||||||
```
|
```
|
||||||
|
|
||||||
java:
|
java:
|
||||||
|
@ -221,6 +221,30 @@ class SolutionDP2:
|
|||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
```go
|
||||||
|
func numDistinct(s string, t string) int {
|
||||||
|
dp:= make([][]int,len(s)+1)
|
||||||
|
for i:=0;i<len(dp);i++{
|
||||||
|
dp[i] = make([]int,len(t)+1)
|
||||||
|
}
|
||||||
|
// 初始化
|
||||||
|
for i:=0;i<len(dp);i++{
|
||||||
|
dp[i][0] = 1
|
||||||
|
}
|
||||||
|
// dp[0][j] 为 0,默认值,因此不需要初始化
|
||||||
|
for i:=1;i<len(dp);i++{
|
||||||
|
for j:=1;j<len(dp[i]);j++{
|
||||||
|
if s[i-1] == t[j-1]{
|
||||||
|
dp[i][j] = dp[i-1][j-1] + dp[i-1][j]
|
||||||
|
}else{
|
||||||
|
dp[i][j] = dp[i-1][j]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dp[len(dp)-1][len(dp[0])-1]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
Javascript:
|
Javascript:
|
||||||
```javascript
|
```javascript
|
||||||
|
@ -200,6 +200,7 @@ public:
|
|||||||
|
|
||||||
Java:
|
Java:
|
||||||
```java
|
```java
|
||||||
|
// 解法1
|
||||||
class Solution {
|
class Solution {
|
||||||
public int canCompleteCircuit(int[] gas, int[] cost) {
|
public int canCompleteCircuit(int[] gas, int[] cost) {
|
||||||
int sum = 0;
|
int sum = 0;
|
||||||
@ -221,7 +222,26 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
```java
|
||||||
|
// 解法2
|
||||||
|
class Solution {
|
||||||
|
public int canCompleteCircuit(int[] gas, int[] cost) {
|
||||||
|
int curSum = 0;
|
||||||
|
int totalSum = 0;
|
||||||
|
int index = 0;
|
||||||
|
for (int i = 0; i < gas.length; i++) {
|
||||||
|
curSum += gas[i] - cost[i];
|
||||||
|
totalSum += gas[i] - cost[i];
|
||||||
|
if (curSum < 0) {
|
||||||
|
index = (i + 1) % gas.length ;
|
||||||
|
curSum = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (totalSum < 0) return -1;
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
Python:
|
Python:
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
@ -283,6 +303,35 @@ var canCompleteCircuit = function(gas, cost) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
C:
|
||||||
|
```c
|
||||||
|
int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){
|
||||||
|
int curSum = 0;
|
||||||
|
int i;
|
||||||
|
int min = INT_MAX;
|
||||||
|
//遍历整个数组。计算出每站的用油差。并将其与最小累加量比较
|
||||||
|
for(i = 0; i < gasSize; i++) {
|
||||||
|
int diff = gas[i] - cost[i];
|
||||||
|
curSum += diff;
|
||||||
|
if(curSum < min)
|
||||||
|
min = curSum;
|
||||||
|
}
|
||||||
|
//若汽油总数为负数,代表无法跑完一环。返回-1
|
||||||
|
if(curSum < 0)
|
||||||
|
return -1;
|
||||||
|
//若min大于等于0,说明每一天加油量比用油量多。因此从0出发即可
|
||||||
|
if(min >= 0)
|
||||||
|
return 0;
|
||||||
|
//若累加最小值为负,则找到一个非零元素(加油量大于出油量)出发。返回坐标
|
||||||
|
for(i = gasSize - 1; i >= 0; i--) {
|
||||||
|
min+=(gas[i]-cost[i]);
|
||||||
|
if(min >= 0)
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
//逻辑上不会返回这个0
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
@ -467,6 +467,85 @@ function reverse(strArr, start, end) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Swift:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
func reverseWords(_ s: String) -> String {
|
||||||
|
var stringArr = removeSpace(s)
|
||||||
|
reverseString(&stringArr, startIndex: 0, endIndex: stringArr.count - 1)
|
||||||
|
reverseWord(&stringArr)
|
||||||
|
return String(stringArr)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 1、移除多余的空格(前后所有的空格,中间只留一个空格)
|
||||||
|
func removeSpace(_ s: String) -> [Character] {
|
||||||
|
let ch = Array(s)
|
||||||
|
var left = 0
|
||||||
|
var right = ch.count - 1
|
||||||
|
// 忽略字符串前面的所有空格
|
||||||
|
while ch[left] == " " {
|
||||||
|
left += 1
|
||||||
|
}
|
||||||
|
// 忽略字符串后面的所有空格
|
||||||
|
while ch[right] == " " {
|
||||||
|
right -= 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// 接下来就是要处理中间的多余空格
|
||||||
|
var lastArr = Array<Character>()
|
||||||
|
while left <= right {
|
||||||
|
// 准备加到新字符串当中的字符
|
||||||
|
let char = ch[left]
|
||||||
|
// 新的字符串的最后一个字符;或者原字符串中,准备加到新字符串的那个字符;这两个字符当中,只要有一个不是空格,就可以加到新的字符串当中
|
||||||
|
if char != " " || lastArr[lastArr.count - 1] != " " {
|
||||||
|
lastArr.append(char)
|
||||||
|
}
|
||||||
|
|
||||||
|
left += 1
|
||||||
|
}
|
||||||
|
return lastArr
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 2、反转整个字符串
|
||||||
|
func reverseString(_ s: inout [Character], startIndex: Int, endIndex: Int) {
|
||||||
|
var start = startIndex
|
||||||
|
var end = endIndex
|
||||||
|
while start < end {
|
||||||
|
(s[start], s[end]) = (s[end], s[start])
|
||||||
|
start += 1
|
||||||
|
end -= 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 3、再次将字符串里面的单词反转
|
||||||
|
func reverseWord(_ s: inout [Character]) {
|
||||||
|
var start = 0
|
||||||
|
var end = 0
|
||||||
|
var entry = false
|
||||||
|
|
||||||
|
for i in 0..<s.count {
|
||||||
|
if !entry {
|
||||||
|
start = i
|
||||||
|
entry = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if entry && s[i] == " " && s[i - 1] != " " {
|
||||||
|
end = i - 1
|
||||||
|
entry = false
|
||||||
|
reverseString(&s, startIndex: start, endIndex: end)
|
||||||
|
}
|
||||||
|
|
||||||
|
if entry && (i == s.count - 1) && s[i] != " " {
|
||||||
|
end = i
|
||||||
|
entry = false
|
||||||
|
reverseString(&s, startIndex: start, endIndex: end)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -191,7 +191,68 @@ var isHappy = function(n) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Swift:
|
||||||
|
```swift
|
||||||
|
// number 每个位置上的数字的平方和
|
||||||
|
func getSum(_ number: Int) -> Int {
|
||||||
|
var sum = 0
|
||||||
|
var num = number
|
||||||
|
while num > 0 {
|
||||||
|
let temp = num % 10
|
||||||
|
sum += (temp * temp)
|
||||||
|
num /= 10
|
||||||
|
}
|
||||||
|
return sum
|
||||||
|
}
|
||||||
|
func isHappy(_ n: Int) -> Bool {
|
||||||
|
var set = Set<Int>()
|
||||||
|
var num = n
|
||||||
|
while true {
|
||||||
|
let sum = self.getSum(num)
|
||||||
|
if sum == 1 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
// 如果这个sum曾经出现过,说明已经陷入了无限循环了
|
||||||
|
if set.contains(sum) {
|
||||||
|
return false
|
||||||
|
} else {
|
||||||
|
set.insert(sum)
|
||||||
|
}
|
||||||
|
num = sum
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
PHP:
|
||||||
|
```php
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* @param Integer $n
|
||||||
|
* @return Boolean
|
||||||
|
*/
|
||||||
|
function isHappy($n) {
|
||||||
|
// use a set to record sum
|
||||||
|
// whenever there is a duplicated, stop
|
||||||
|
// == 1 return true, else false
|
||||||
|
$table = [];
|
||||||
|
while ($n != 1 && !isset($table[$n])) {
|
||||||
|
$table[$n] = 1;
|
||||||
|
$n = self::getNextN($n);
|
||||||
|
}
|
||||||
|
return $n == 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getNextN(int $n) {
|
||||||
|
$res = 0;
|
||||||
|
while ($n > 0) {
|
||||||
|
$temp = $n % 10;
|
||||||
|
$res += $temp * $temp;
|
||||||
|
$n = floor($n / 10);
|
||||||
|
}
|
||||||
|
return $res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
@ -331,8 +331,32 @@ func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
PHP:
|
||||||
|
```php
|
||||||
|
/**
|
||||||
|
* Definition for singly-linked list.
|
||||||
|
* type ListNode struct {
|
||||||
|
* Val int
|
||||||
|
* Next *ListNode
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
// 虚拟头+双指针
|
||||||
|
func removeElements(head *ListNode, val int) *ListNode {
|
||||||
|
dummyHead := &ListNode{}
|
||||||
|
dummyHead.Next = head
|
||||||
|
pred := dummyHead
|
||||||
|
cur := head
|
||||||
|
for cur != nil {
|
||||||
|
if cur.Val == val {
|
||||||
|
pred.Next = cur.Next
|
||||||
|
} else {
|
||||||
|
pred = cur
|
||||||
|
}
|
||||||
|
cur = cur.Next
|
||||||
|
}
|
||||||
|
return dummyHead.Next
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
@ -264,6 +264,34 @@ impl Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
PHP:
|
||||||
|
```php
|
||||||
|
// 双指针 - 滑动窗口
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* @param Integer $target
|
||||||
|
* @param Integer[] $nums
|
||||||
|
* @return Integer
|
||||||
|
*/
|
||||||
|
function minSubArrayLen($target, $nums) {
|
||||||
|
if (count($nums) < 1) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
$sum = 0;
|
||||||
|
$res = PHP_INT_MAX;
|
||||||
|
$left = 0;
|
||||||
|
for ($right = 0; $right < count($nums); $right++) {
|
||||||
|
$sum += $nums[$right];
|
||||||
|
while ($sum >= $target) {
|
||||||
|
$res = min($res, $right - $left + 1);
|
||||||
|
$sum -= $nums[$left];
|
||||||
|
$left++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $res == PHP_INT_MAX ? 0 : $res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
@ -204,7 +204,27 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
```java
|
||||||
|
class Solution {
|
||||||
|
// 迭代法
|
||||||
|
public int countNodes(TreeNode root) {
|
||||||
|
if (root == null) return 0;
|
||||||
|
Queue<TreeNode> queue = new LinkedList<>();
|
||||||
|
queue.offer(root);
|
||||||
|
int result = 0;
|
||||||
|
while (!queue.isEmpty()) {
|
||||||
|
int size = queue.size();
|
||||||
|
while (size -- > 0) {
|
||||||
|
TreeNode cur = queue.poll();
|
||||||
|
result++;
|
||||||
|
if (cur.left != null) queue.offer(cur.left);
|
||||||
|
if (cur.right != null) queue.offer(cur.right);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
```java
|
```java
|
||||||
class Solution {
|
class Solution {
|
||||||
/**
|
/**
|
||||||
|
@ -359,6 +359,71 @@ class MyStack:
|
|||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
|
```go
|
||||||
|
type MyStack struct {
|
||||||
|
queue []int//创建一个队列
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** Initialize your data structure here. */
|
||||||
|
func Constructor() MyStack {
|
||||||
|
return MyStack{ //初始化
|
||||||
|
queue:make([]int,0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** Push element x onto stack. */
|
||||||
|
func (this *MyStack) Push(x int) {
|
||||||
|
//添加元素
|
||||||
|
this.queue=append(this.queue,x)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** Removes the element on top of the stack and returns that element. */
|
||||||
|
func (this *MyStack) Pop() int {
|
||||||
|
n:=len(this.queue)-1//判断长度
|
||||||
|
for n!=0{ //除了最后一个,其余的都重新添加到队列里
|
||||||
|
val:=this.queue[0]
|
||||||
|
this.queue=this.queue[1:]
|
||||||
|
this.queue=append(this.queue,val)
|
||||||
|
n--
|
||||||
|
}
|
||||||
|
//弹出元素
|
||||||
|
val:=this.queue[0]
|
||||||
|
this.queue=this.queue[1:]
|
||||||
|
return val
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** Get the top element. */
|
||||||
|
func (this *MyStack) Top() int {
|
||||||
|
//利用Pop函数,弹出来的元素重新添加
|
||||||
|
val:=this.Pop()
|
||||||
|
this.queue=append(this.queue,val)
|
||||||
|
return val
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** Returns whether the stack is empty. */
|
||||||
|
func (this *MyStack) Empty() bool {
|
||||||
|
return len(this.queue)==0
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Your MyStack object will be instantiated and called as such:
|
||||||
|
* obj := Constructor();
|
||||||
|
* obj.Push(x);
|
||||||
|
* param_2 := obj.Pop();
|
||||||
|
* param_3 := obj.Top();
|
||||||
|
* param_4 := obj.Empty();
|
||||||
|
*/
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
javaScript:
|
javaScript:
|
||||||
|
|
||||||
使用数组(push, shift)模拟队列
|
使用数组(push, shift)模拟队列
|
||||||
|
@ -205,33 +205,26 @@ class MyQueue:
|
|||||||
|
|
||||||
def pop(self) -> int:
|
def pop(self) -> int:
|
||||||
"""
|
"""
|
||||||
1. 检查如果out里面元素,则直接pop
|
Removes the element from in front of queue and returns that element.
|
||||||
2. 如果out没有元素,就把in里面的元素(除了第一个)依次pop后装进out里面
|
|
||||||
3. 直接把in剩下的元素pop出来,就是queue头部的
|
|
||||||
"""
|
"""
|
||||||
if self.empty:
|
if self.empty():
|
||||||
return None
|
return None
|
||||||
|
|
||||||
if self.stack_out:
|
if self.stack_out:
|
||||||
return self.stack_out.pop()
|
return self.stack_out.pop()
|
||||||
else:
|
else:
|
||||||
for i in range(1, len(self.stack_in)):
|
for i in range(len(self.stack_in)):
|
||||||
self.stack_out.append(self.stack_in.pop())
|
self.stack_out.append(self.stack_in.pop())
|
||||||
return self.stack_in.pop()
|
return self.stack_out.pop()
|
||||||
|
|
||||||
|
|
||||||
def peek(self) -> int:
|
def peek(self) -> int:
|
||||||
"""
|
"""
|
||||||
1. 查out有没有元素,有就把最上面的返回
|
Get the front element.
|
||||||
2. 如果out没有元素,就把in最下面的返回
|
|
||||||
"""
|
"""
|
||||||
if self.empty:
|
ans = self.pop()
|
||||||
return None
|
self.stack_out.append(ans)
|
||||||
|
return ans
|
||||||
if self.stack_out:
|
|
||||||
return self.stack_out[-1]
|
|
||||||
else:
|
|
||||||
return self.stack_in[0]
|
|
||||||
|
|
||||||
|
|
||||||
def empty(self) -> bool:
|
def empty(self) -> bool:
|
||||||
|
@ -144,6 +144,75 @@ public:
|
|||||||
## Java
|
## Java
|
||||||
|
|
||||||
```java
|
```java
|
||||||
|
// 方法一,使用数组
|
||||||
|
class Solution {
|
||||||
|
public boolean isPalindrome(ListNode head) {
|
||||||
|
int len = 0;
|
||||||
|
// 统计链表长度
|
||||||
|
ListNode cur = head;
|
||||||
|
while (cur != null) {
|
||||||
|
len++;
|
||||||
|
cur = cur.next;
|
||||||
|
}
|
||||||
|
cur = head;
|
||||||
|
int[] res = new int[len];
|
||||||
|
// 将元素加到数组之中
|
||||||
|
for (int i = 0; i < res.length; i++){
|
||||||
|
res[i] = cur.val;
|
||||||
|
cur = cur.next;
|
||||||
|
}
|
||||||
|
// 比较回文
|
||||||
|
for (int i = 0, j = len - 1; i < j; i++, j--){
|
||||||
|
if (res[i] != res[j]){
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 方法二,快慢指针
|
||||||
|
class Solution {
|
||||||
|
public boolean isPalindrome(ListNode head) {
|
||||||
|
// 如果为空或者仅有一个节点,返回true
|
||||||
|
if (head == null && head.next == null) return true;
|
||||||
|
ListNode slow = head;
|
||||||
|
ListNode fast = head;
|
||||||
|
ListNode pre = head;
|
||||||
|
while (fast != null && fast.next != null){
|
||||||
|
pre = slow; // 记录slow的前一个结点
|
||||||
|
slow = slow.next;
|
||||||
|
fast = fast.next.next;
|
||||||
|
}
|
||||||
|
pre.next = null; // 分割两个链表
|
||||||
|
|
||||||
|
// 前半部分
|
||||||
|
ListNode cur1 = head;
|
||||||
|
// 后半部分。这里使用了反转链表
|
||||||
|
ListNode cur2 = reverseList(slow);
|
||||||
|
|
||||||
|
while (cur1 != null){
|
||||||
|
if (cur1.val != cur2.val) return false;
|
||||||
|
|
||||||
|
// 注意要移动两个结点
|
||||||
|
cur1 = cur1.next;
|
||||||
|
cur2 = cur2.next;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
ListNode reverseList(ListNode head){
|
||||||
|
// 反转链表
|
||||||
|
ListNode tmp = null;
|
||||||
|
ListNode pre = null;
|
||||||
|
while (head != null){
|
||||||
|
tmp = head.next;
|
||||||
|
head.next = pre;
|
||||||
|
pre = head;
|
||||||
|
head = tmp;
|
||||||
|
}
|
||||||
|
return pre;
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
## Python
|
## Python
|
||||||
@ -209,11 +278,13 @@ class Solution:
|
|||||||
## Go
|
## Go
|
||||||
|
|
||||||
```go
|
```go
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## JavaScript
|
## JavaScript
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
@ -221,6 +221,41 @@ func isAnagram(_ s: String, _ t: String) -> Bool {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
PHP:
|
||||||
|
```php
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* @param String $s
|
||||||
|
* @param String $t
|
||||||
|
* @return Boolean
|
||||||
|
*/
|
||||||
|
function isAnagram($s, $t) {
|
||||||
|
if (strlen($s) != strlen($t)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
$table = [];
|
||||||
|
for ($i = 0; $i < strlen($s); $i++) {
|
||||||
|
if (!isset($table[$s[$i]])) {
|
||||||
|
$table[$s[$i]] = 1;
|
||||||
|
} else {
|
||||||
|
$table[$s[$i]]++;
|
||||||
|
}
|
||||||
|
if (!isset($table[$t[$i]])) {
|
||||||
|
$table[$t[$i]] = -1;
|
||||||
|
} else {
|
||||||
|
$table[$t[$i]]--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach ($table as $record) {
|
||||||
|
if ($record != 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## 相关题目
|
## 相关题目
|
||||||
|
|
||||||
* 383.赎金信
|
* 383.赎金信
|
||||||
|
@ -189,6 +189,79 @@ class Solution:
|
|||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
|
```go
|
||||||
|
//方法一:小顶堆
|
||||||
|
func topKFrequent(nums []int, k int) []int {
|
||||||
|
map_num:=map[int]int{}
|
||||||
|
//记录每个元素出现的次数
|
||||||
|
for _,item:=range nums{
|
||||||
|
map_num[item]++
|
||||||
|
}
|
||||||
|
h:=&IHeap{}
|
||||||
|
heap.Init(h)
|
||||||
|
//所有元素入堆,堆的长度为k
|
||||||
|
for key,value:=range map_num{
|
||||||
|
heap.Push(h,[2]int{key,value})
|
||||||
|
if h.Len()>k{
|
||||||
|
heap.Pop(h)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res:=make([]int,k)
|
||||||
|
//按顺序返回堆中的元素
|
||||||
|
for i:=0;i<k;i++{
|
||||||
|
res[k-i-1]=heap.Pop(h).([2]int)[0]
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
//构建小顶堆
|
||||||
|
type IHeap [][2]int
|
||||||
|
|
||||||
|
func (h IHeap) Len()int {
|
||||||
|
return len(h)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h IHeap) Less (i,j int) bool {
|
||||||
|
return h[i][1]<h[j][1]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h IHeap) Swap(i,j int) {
|
||||||
|
h[i],h[j]=h[j],h[i]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *IHeap) Push(x interface{}){
|
||||||
|
*h=append(*h,x.([2]int))
|
||||||
|
}
|
||||||
|
func (h *IHeap) Pop() interface{}{
|
||||||
|
old:=*h
|
||||||
|
n:=len(old)
|
||||||
|
x:=old[n-1]
|
||||||
|
*h=old[0:n-1]
|
||||||
|
return x
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//方法二:利用O(logn)排序
|
||||||
|
func topKFrequent(nums []int, k int) []int {
|
||||||
|
ans:=[]int{}
|
||||||
|
map_num:=map[int]int{}
|
||||||
|
for _,item:=range nums {
|
||||||
|
map_num[item]++
|
||||||
|
}
|
||||||
|
for key,_:=range map_num{
|
||||||
|
ans=append(ans,key)
|
||||||
|
}
|
||||||
|
//核心思想:排序
|
||||||
|
//可以不用包函数,自己实现快排
|
||||||
|
sort.Slice(ans,func (a,b int)bool{
|
||||||
|
return map_num[ans[a]]>map_num[ans[b]]
|
||||||
|
})
|
||||||
|
return ans[:k]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
javaScript:
|
javaScript:
|
||||||
```js
|
```js
|
||||||
|
@ -209,6 +209,35 @@ func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
PHP:
|
||||||
|
```php
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* @param Integer[] $nums1
|
||||||
|
* @param Integer[] $nums2
|
||||||
|
* @return Integer[]
|
||||||
|
*/
|
||||||
|
function intersection($nums1, $nums2) {
|
||||||
|
if (count($nums1) == 0 || count($nums2) == 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
$counts = [];
|
||||||
|
$res = [];
|
||||||
|
foreach ($nums1 as $num) {
|
||||||
|
$counts[$num] = 1;
|
||||||
|
}
|
||||||
|
foreach ($nums2 as $num) {
|
||||||
|
if (isset($counts[$num])) {
|
||||||
|
$res[] = $num;
|
||||||
|
}
|
||||||
|
unset($counts[$num]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## 相关题目
|
## 相关题目
|
||||||
|
|
||||||
* 350.两个数组的交集 II
|
* 350.两个数组的交集 II
|
||||||
|
@ -267,6 +267,54 @@ var canConstruct = function(ransomNote, magazine) {
|
|||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
PHP:
|
||||||
|
```php
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* @param String $ransomNote
|
||||||
|
* @param String $magazine
|
||||||
|
* @return Boolean
|
||||||
|
*/
|
||||||
|
function canConstruct($ransomNote, $magazine) {
|
||||||
|
if (count($ransomNote) > count($magazine)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
$map = [];
|
||||||
|
for ($i = 0; $i < strlen($magazine); $i++) {
|
||||||
|
$map[$magazine[$i]] = ($map[$magazine[$i]] ?? 0) + 1;
|
||||||
|
}
|
||||||
|
for ($i = 0; $i < strlen($ransomNote); $i++) {
|
||||||
|
if (!isset($map[$ransomNote[$i]]) || --$map[$ransomNote[$i]] < 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Swift:
|
||||||
|
```swift
|
||||||
|
func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool {
|
||||||
|
var record = Array(repeating: 0, count: 26);
|
||||||
|
let aUnicodeScalarValue = "a".unicodeScalars.first!.value
|
||||||
|
for unicodeScalar in magazine.unicodeScalars {
|
||||||
|
// 通过record 记录 magazine 里各个字符出现的次数
|
||||||
|
let idx: Int = Int(unicodeScalar.value - aUnicodeScalarValue)
|
||||||
|
record[idx] += 1
|
||||||
|
}
|
||||||
|
for unicodeScalar in ransomNote.unicodeScalars {
|
||||||
|
// 遍历 ransomNote,在record里对应的字符个数做 -- 操作
|
||||||
|
let idx: Int = Int(unicodeScalar.value - aUnicodeScalarValue)
|
||||||
|
record[idx] -= 1
|
||||||
|
// 如果小于零说明在magazine没有
|
||||||
|
if record[idx] < 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
@ -203,6 +203,25 @@ const isSubsequence = (s, t) => {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Go:
|
||||||
|
```go
|
||||||
|
func isSubsequence(s string, t string) bool {
|
||||||
|
dp := make([][]int,len(s)+1)
|
||||||
|
for i:=0;i<len(dp);i++{
|
||||||
|
dp[i] = make([]int,len(t)+1)
|
||||||
|
}
|
||||||
|
for i:=1;i<len(dp);i++{
|
||||||
|
for j:=1;j<len(dp[i]);j++{
|
||||||
|
if s[i-1] == t[j-1]{
|
||||||
|
dp[i][j] = dp[i-1][j-1] +1
|
||||||
|
}else{
|
||||||
|
dp[i][j] = dp[i][j-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dp[len(s)][len(t)]==len(s)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -201,7 +201,31 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
```java
|
||||||
|
// 层序遍历迭代法
|
||||||
|
class Solution {
|
||||||
|
public int sumOfLeftLeaves(TreeNode root) {
|
||||||
|
int sum = 0;
|
||||||
|
if (root == null) return 0;
|
||||||
|
Queue<TreeNode> queue = new LinkedList<>();
|
||||||
|
queue.offer(root);
|
||||||
|
while (!queue.isEmpty()) {
|
||||||
|
int size = queue.size();
|
||||||
|
while (size -- > 0) {
|
||||||
|
TreeNode node = queue.poll();
|
||||||
|
if (node.left != null) { // 左节点不为空
|
||||||
|
queue.offer(node.left);
|
||||||
|
if (node.left.left == null && node.left.right == null){ // 左叶子节点
|
||||||
|
sum += node.left.val;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (node.right != null) queue.offer(node.right);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sum;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
## Python
|
## Python
|
||||||
|
@ -218,6 +218,30 @@ var findMinArrowShots = function(points) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
C:
|
||||||
|
```c
|
||||||
|
int cmp(const void *a,const void *b)
|
||||||
|
{
|
||||||
|
return ((*((int**)a))[0] > (*((int**)b))[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
int findMinArrowShots(int** points, int pointsSize, int* pointsColSize){
|
||||||
|
//将points数组作升序排序
|
||||||
|
qsort(points, pointsSize, sizeof(points[0]),cmp);
|
||||||
|
|
||||||
|
int arrowNum = 1;
|
||||||
|
int i = 1;
|
||||||
|
for(i = 1; i < pointsSize; i++) {
|
||||||
|
//若前一个气球与当前气球不重叠,证明需要增加箭的数量
|
||||||
|
if(points[i][0] > points[i-1][1])
|
||||||
|
arrowNum++;
|
||||||
|
else
|
||||||
|
//若前一个气球与当前气球重叠,判断并更新最小的x_end
|
||||||
|
points[i][1] = points[i][1] > points[i-1][1] ? points[i-1][1] : points[i][1];
|
||||||
|
}
|
||||||
|
return arrowNum;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
@ -221,6 +221,66 @@ var fourSumCount = function(nums1, nums2, nums3, nums4) {
|
|||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
PHP:
|
||||||
|
```php
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* @param Integer[] $nums1
|
||||||
|
* @param Integer[] $nums2
|
||||||
|
* @param Integer[] $nums3
|
||||||
|
* @param Integer[] $nums4
|
||||||
|
* @return Integer
|
||||||
|
*/
|
||||||
|
function fourSumCount($nums1, $nums2, $nums3, $nums4) {
|
||||||
|
$map = [];
|
||||||
|
foreach ($nums1 as $n1) {
|
||||||
|
foreach ($nums2 as $n2) {
|
||||||
|
$temp = $n1 + $n2;
|
||||||
|
$map[$temp] = isset($map[$temp]) ? $map[$temp]+1 : 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$count = 0;
|
||||||
|
foreach ($nums3 as $n3) {
|
||||||
|
foreach ($nums4 as $n4) {
|
||||||
|
$temp = 0 - $n3 - $n4;
|
||||||
|
if (isset($map[$temp])) {
|
||||||
|
$count += $map[$temp];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Swift:
|
||||||
|
```swift
|
||||||
|
func fourSumCount(_ nums1: [Int], _ nums2: [Int], _ nums3: [Int], _ nums4: [Int]) -> Int {
|
||||||
|
// key:a+b的数值,value:a+b数值出现的次数
|
||||||
|
var map = [Int: Int]()
|
||||||
|
// 遍历nums1和nums2数组,统计两个数组元素之和,和出现的次数,放到map中
|
||||||
|
for i in 0 ..< nums1.count {
|
||||||
|
for j in 0 ..< nums2.count {
|
||||||
|
let sum1 = nums1[i] + nums2[j]
|
||||||
|
map[sum1] = (map[sum1] ?? 0) + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 统计a+b+c+d = 0 出现的次数
|
||||||
|
var res = 0
|
||||||
|
// 在遍历大num3和num4数组,找到如果 0-(c+d) 在map中出现过的话,就把map中key对应的value也就是出现次数统计出来。
|
||||||
|
for i in 0 ..< nums3.count {
|
||||||
|
for j in 0 ..< nums4.count {
|
||||||
|
let sum2 = nums3[i] + nums4[j]
|
||||||
|
let other = 0 - sum2
|
||||||
|
if map.keys.contains(other) {
|
||||||
|
res += map[other]!
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
@ -197,11 +197,10 @@ func findContentChildren(g []int, s []int) int {
|
|||||||
|
|
||||||
return child
|
return child
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Javascript:
|
Javascript:
|
||||||
```Javascript
|
```
|
||||||
|
|
||||||
var findContentChildren = function(g, s) {
|
var findContentChildren = function(g, s) {
|
||||||
g = g.sort((a, b) => a - b)
|
g = g.sort((a, b) => a - b)
|
||||||
s = s.sort((a, b) => a - b)
|
s = s.sort((a, b) => a - b)
|
||||||
|
@ -265,7 +265,7 @@ func getMinimumDifference(root *TreeNode) int {
|
|||||||
```
|
```
|
||||||
|
|
||||||
## JavaScript
|
## JavaScript
|
||||||
|
递归 先转换为有序数组
|
||||||
```javascript
|
```javascript
|
||||||
/**
|
/**
|
||||||
* Definition for a binary tree node.
|
* Definition for a binary tree node.
|
||||||
@ -297,6 +297,47 @@ var getMinimumDifference = function (root) {
|
|||||||
return diff;
|
return diff;
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
递归 在递归的过程中更新最小值
|
||||||
|
```js
|
||||||
|
var getMinimumDifference = function(root) {
|
||||||
|
let res = Infinity
|
||||||
|
let preNode = null
|
||||||
|
// 中序遍历
|
||||||
|
const inorder = (node) => {
|
||||||
|
if(!node) return
|
||||||
|
inorder(node.left)
|
||||||
|
// 更新res
|
||||||
|
if(preNode) res = Math.min(res, node.val - preNode.val)
|
||||||
|
// 记录前一个节点
|
||||||
|
preNode = node
|
||||||
|
inorder(node.right)
|
||||||
|
}
|
||||||
|
inorder(root)
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
迭代 中序遍历
|
||||||
|
```js
|
||||||
|
var getMinimumDifference = function(root) {
|
||||||
|
let stack = []
|
||||||
|
let cur = root
|
||||||
|
let res = Infinity
|
||||||
|
let pre = null
|
||||||
|
while(cur || stack.length) {
|
||||||
|
if(cur) {
|
||||||
|
stack.push(cur)
|
||||||
|
cur = cur.left
|
||||||
|
} else {
|
||||||
|
cur = stack.pop()
|
||||||
|
if(pre) res = Math.min(res, cur.val - pre.val)
|
||||||
|
pre = cur
|
||||||
|
cur = cur.right
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
@ -147,8 +147,38 @@ class Solution:
|
|||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
```go
|
||||||
|
func minDistance(word1 string, word2 string) int {
|
||||||
|
dp := make([][]int, len(word1)+1)
|
||||||
|
for i := 0; i < len(dp); i++ {
|
||||||
|
dp[i] = make([]int, len(word2)+1)
|
||||||
|
}
|
||||||
|
//初始化
|
||||||
|
for i := 0; i < len(dp); i++ {
|
||||||
|
dp[i][0] = i
|
||||||
|
}
|
||||||
|
for j := 0; j < len(dp[0]); j++ {
|
||||||
|
dp[0][j] = j
|
||||||
|
}
|
||||||
|
for i := 1; i < len(dp); i++ {
|
||||||
|
for j := 1; j < len(dp[i]); j++ {
|
||||||
|
if word1[i-1] == word2[j-1] {
|
||||||
|
dp[i][j] = dp[i-1][j-1]
|
||||||
|
} else {
|
||||||
|
dp[i][j] = min(min(dp[i-1][j]+1, dp[i][j-1]+1), dp[i-1][j-1]+2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dp[len(dp)-1][len(dp[0])-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
func min(a, b int) int {
|
||||||
|
if a < b {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
```
|
||||||
Javascript:
|
Javascript:
|
||||||
```javascript
|
```javascript
|
||||||
const minDistance = (word1, word2) => {
|
const minDistance = (word1, word2) => {
|
||||||
|
@ -478,6 +478,38 @@ int search(int* nums, int numsSize, int target){
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**PHP:**
|
||||||
|
```php
|
||||||
|
// 左闭右闭区间
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* @param Integer[] $nums
|
||||||
|
* @param Integer $target
|
||||||
|
* @return Integer
|
||||||
|
*/
|
||||||
|
function search($nums, $target) {
|
||||||
|
if (count($nums) == 0) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
$left = 0;
|
||||||
|
$right = count($nums) - 1;
|
||||||
|
while ($left <= $right) {
|
||||||
|
$mid = floor(($left + $right) / 2);
|
||||||
|
if ($nums[$mid] == $target) {
|
||||||
|
return $mid;
|
||||||
|
}
|
||||||
|
if ($nums[$mid] > $target) {
|
||||||
|
$right = $mid - 1;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
$left = $mid + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||||
|
@ -152,6 +152,25 @@ class Solution:
|
|||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
```Go
|
||||||
|
func maxProfit(prices []int, fee int) int {
|
||||||
|
n := len(prices)
|
||||||
|
dp := make([][2]int, n)
|
||||||
|
dp[0][0] = -prices[0]
|
||||||
|
for i := 1; i < n; i++ {
|
||||||
|
dp[i][1] = max(dp[i-1][1], dp[i-1][0]+prices[i]-fee)
|
||||||
|
dp[i][0] = max(dp[i-1][0], dp[i-1][1]-prices[i])
|
||||||
|
}
|
||||||
|
return dp[n-1][1]
|
||||||
|
}
|
||||||
|
|
||||||
|
func max(a, b int) int {
|
||||||
|
if a > b {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Javascript:
|
Javascript:
|
||||||
```javascript
|
```javascript
|
||||||
|
@ -368,7 +368,34 @@ class Solution:
|
|||||||
return result
|
return result
|
||||||
```
|
```
|
||||||
Go:
|
Go:
|
||||||
|
```go
|
||||||
|
const inf = math.MaxInt64 / 2
|
||||||
|
|
||||||
|
func minCameraCover(root *TreeNode) int {
|
||||||
|
var dfs func(*TreeNode) (a, b, c int)
|
||||||
|
dfs = func(node *TreeNode) (a, b, c int) {
|
||||||
|
if node == nil {
|
||||||
|
return inf, 0, 0
|
||||||
|
}
|
||||||
|
lefta, leftb, leftc := dfs(node.Left)
|
||||||
|
righta, rightb, rightc := dfs(node.Right)
|
||||||
|
a = leftc + rightc + 1
|
||||||
|
b = min(a, min(lefta+rightb, righta+leftb))
|
||||||
|
c = min(a, leftb+rightb)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, ans, _ := dfs(root)
|
||||||
|
return ans
|
||||||
|
}
|
||||||
|
|
||||||
|
func min(a, b int) int {
|
||||||
|
if a <= b {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
Javascript:
|
Javascript:
|
||||||
```Javascript
|
```Javascript
|
||||||
var minCameraCover = function(root) {
|
var minCameraCover = function(root) {
|
||||||
|
@ -271,6 +271,69 @@ end
|
|||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
C:
|
||||||
|
```c
|
||||||
|
int* sortedSquares(int* nums, int numsSize, int* returnSize){
|
||||||
|
//返回的数组大小就是原数组大小
|
||||||
|
*returnSize = numsSize;
|
||||||
|
//创建两个指针,right指向数组最后一位元素,left指向数组第一位元素
|
||||||
|
int right = numsSize - 1;
|
||||||
|
int left = 0;
|
||||||
|
|
||||||
|
//最后要返回的结果数组
|
||||||
|
int* ans = (int*)malloc(sizeof(int) * numsSize);
|
||||||
|
int index;
|
||||||
|
for(index = numsSize - 1; index >= 0; index--) {
|
||||||
|
//左指针指向元素的平方
|
||||||
|
int lSquare = nums[left] * nums[left];
|
||||||
|
//右指针指向元素的平方
|
||||||
|
int rSquare = nums[right] * nums[right];
|
||||||
|
//若左指针指向元素平方比右指针指向元素平方大,将左指针指向元素平方放入结果数组。左指针右移一位
|
||||||
|
if(lSquare > rSquare) {
|
||||||
|
ans[index] = lSquare;
|
||||||
|
left++;
|
||||||
|
}
|
||||||
|
//若右指针指向元素平方比左指针指向元素平方大,将右指针指向元素平方放入结果数组。右指针左移一位
|
||||||
|
else {
|
||||||
|
ans[index] = rSquare;
|
||||||
|
right--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//返回结果数组
|
||||||
|
return ans;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
PHP:
|
||||||
|
```php
|
||||||
|
class Solution {
|
||||||
|
/**
|
||||||
|
* @param Integer[] $nums
|
||||||
|
* @return Integer[]
|
||||||
|
*/
|
||||||
|
function sortedSquares($nums) {
|
||||||
|
// 双指针法
|
||||||
|
$res = [];
|
||||||
|
for ($i = 0; $i < count($nums); $i++) {
|
||||||
|
$res[$i] = 0;
|
||||||
|
}
|
||||||
|
$k = count($nums) - 1;
|
||||||
|
for ($i = 0, $j = count($nums) - 1; $i <= $j; ) {
|
||||||
|
if ($nums[$i] ** 2 < $nums[$j] ** 2) {
|
||||||
|
$res[$k--] = $nums[$j] ** 2;
|
||||||
|
$j--;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
$res[$k--] = $nums[$i] ** 2;
|
||||||
|
$i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return $res;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
@ -268,6 +268,47 @@ func min(a,b int)int{
|
|||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Swift:
|
||||||
|
```swift
|
||||||
|
func commonChars(_ words: [String]) -> [String] {
|
||||||
|
var res = [String]()
|
||||||
|
if words.count < 1 {
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
let aUnicodeScalarValue = "a".unicodeScalars.first!.value
|
||||||
|
let lettersMaxCount = 26
|
||||||
|
// 用于统计所有字符串每个字母出现的 最小 频率
|
||||||
|
var hash = Array(repeating: 0, count: lettersMaxCount)
|
||||||
|
// 统计第一个字符串每个字母出现的次数
|
||||||
|
for unicodeScalar in words.first!.unicodeScalars {
|
||||||
|
hash[Int(unicodeScalar.value - aUnicodeScalarValue)] += 1
|
||||||
|
}
|
||||||
|
// 统计除第一个字符串每个字母出现的次数
|
||||||
|
for idx in 1 ..< words.count {
|
||||||
|
var hashOtherStr = Array(repeating: 0, count: lettersMaxCount)
|
||||||
|
for unicodeScalar in words[idx].unicodeScalars {
|
||||||
|
hashOtherStr[Int(unicodeScalar.value - aUnicodeScalarValue)] += 1
|
||||||
|
}
|
||||||
|
// 更新hash,保证hash里统计的字母为出现的最小频率
|
||||||
|
for k in 0 ..< lettersMaxCount {
|
||||||
|
hash[k] = min(hash[k], hashOtherStr[k])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 将hash统计的字符次数,转成输出形式
|
||||||
|
for i in 0 ..< lettersMaxCount {
|
||||||
|
while hash[i] != 0 { // 注意这里是while,多个重复的字符
|
||||||
|
let currentUnicodeScalarValue: UInt32 = UInt32(i) + aUnicodeScalarValue
|
||||||
|
let currentUnicodeScalar: UnicodeScalar = UnicodeScalar(currentUnicodeScalarValue)!
|
||||||
|
let outputStr = String(currentUnicodeScalar) // UnicodeScalar -> String
|
||||||
|
res.append(outputStr)
|
||||||
|
hash[i] -= 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||||
|
@ -110,15 +110,16 @@ class Solution {
|
|||||||
int len = nums.length;
|
int len = nums.length;
|
||||||
for (int i = 0; i < len; i++) {
|
for (int i = 0; i < len; i++) {
|
||||||
//从前向后遍历,遇到负数将其变为正数,同时K--
|
//从前向后遍历,遇到负数将其变为正数,同时K--
|
||||||
if (nums[i] < 0 && k > 0) {
|
if (nums[i] < 0 && K > 0) {
|
||||||
nums[i] = -nums[i];
|
nums[i] = -nums[i];
|
||||||
k--;
|
K--;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 如果K还大于0,那么反复转变数值最小的元素,将K用完
|
// 如果K还大于0,那么反复转变数值最小的元素,将K用完
|
||||||
if (k % 2 == 1) nums[len - 1] = -nums[len - 1];
|
|
||||||
|
if (K % 2 == 1) nums[len - 1] = -nums[len - 1];
|
||||||
return Arrays.stream(nums).sum();
|
return Arrays.stream(nums).sum();
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -27,7 +27,7 @@
|
|||||||
|
|
||||||
我们先看一下前序遍历。
|
我们先看一下前序遍历。
|
||||||
|
|
||||||
前序遍历是中左右,每次先处理的是中间节点,那么先将跟节点放入栈中,然后将右孩子加入栈,再加入左孩子。
|
前序遍历是中左右,每次先处理的是中间节点,那么先将根节点放入栈中,然后将右孩子加入栈,再加入左孩子。
|
||||||
|
|
||||||
为什么要先加入 右孩子,再加入左孩子呢? 因为这样出栈的时候才是中左右的顺序。
|
为什么要先加入 右孩子,再加入左孩子呢? 因为这样出栈的时候才是中左右的顺序。
|
||||||
|
|
||||||
@ -140,7 +140,7 @@ public:
|
|||||||
|
|
||||||
# 总结
|
# 总结
|
||||||
|
|
||||||
此时我们用迭代法写出了二叉树的前后中序遍历,大家可以看出前序和中序是完全两种代码风格,并不想递归写法那样代码稍做调整,就可以实现前后中序。
|
此时我们用迭代法写出了二叉树的前后中序遍历,大家可以看出前序和中序是完全两种代码风格,并不像递归写法那样代码稍做调整,就可以实现前后中序。
|
||||||
|
|
||||||
**这是因为前序遍历中访问节点(遍历节点)和处理节点(将元素放进result数组中)可以同步处理,但是中序就无法做到同步!**
|
**这是因为前序遍历中访问节点(遍历节点)和处理节点(将元素放进result数组中)可以同步处理,但是中序就无法做到同步!**
|
||||||
|
|
||||||
|
@ -214,6 +214,34 @@ var reverseLeftWords = function (s, n) {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Swift:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
func reverseLeftWords(_ s: String, _ n: Int) -> String {
|
||||||
|
var ch = Array(s)
|
||||||
|
let len = ch.count
|
||||||
|
// 反转区间[0, n - 1]
|
||||||
|
reverseString(&ch, startIndex: 0, endIndex: n - 1)
|
||||||
|
// 反转区间[n, len - 1]
|
||||||
|
reverseString(&ch, startIndex: n, endIndex: len - 1)
|
||||||
|
// 反转区间[0, len - 1],也就是整个字符串反转
|
||||||
|
reverseString(&ch, startIndex: 0, endIndex: len - 1)
|
||||||
|
return String(ch)
|
||||||
|
}
|
||||||
|
|
||||||
|
func reverseString(_ s: inout [Character], startIndex: Int, endIndex: Int) {
|
||||||
|
var start = startIndex
|
||||||
|
var end = endIndex
|
||||||
|
while start < end {
|
||||||
|
(s[start], s[end]) = (s[end], s[start])
|
||||||
|
start += 1
|
||||||
|
end -= 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user