diff --git a/problems/0005.最长回文子串.md b/problems/0005.最长回文子串.md index 6e407d6e..a76e5765 100644 --- a/problems/0005.最长回文子串.md +++ b/problems/0005.最长回文子串.md @@ -263,21 +263,38 @@ public: Java: ```java -public int[] twoSum(int[] nums, int target) { - int[] res = new int[2]; - if(nums == null || nums.length == 0){ - return res; - } - Map map = new HashMap<>(); - for(int i = 0; i < nums.length; i++){ - int temp = target - nums[i]; - if(map.containsKey(temp)){ - res[1] = i; - res[0] = map.get(temp); +// 双指针 动态规划 +class Solution { + public String longestPalindrome(String s) { + if (s.length() == 0 || s.length() == 1) return s; + int length = 1; + int index = 0; + boolean[][] palindrome = new boolean[s.length()][s.length()]; + for (int i = 0; i < s.length(); i++) { + palindrome[i][i] = true; } - map.put(nums[i], i); + + for (int L = 2; L <= s.length(); L++) { + for (int i = 0; i < s.length(); i++) { + int j = i + L - 1; + if (j >= s.length()) break; + if (s.charAt(i) != s.charAt(j)) { + palindrome[i][j] = false; + } else { + if (j - i < 3) { + palindrome[i][j] = true; + } else { + palindrome[i][j] = palindrome[i + 1][j - 1]; + } + } + if (palindrome[i][j] && j - i + 1 > length) { + length = j - i + 1; + index = i; + } + } + } + return s.substring(index, index + length); } - return res; } ``` diff --git a/problems/0051.N皇后.md b/problems/0051.N皇后.md index 77a2ca59..18b77951 100644 --- a/problems/0051.N皇后.md +++ b/problems/0051.N皇后.md @@ -222,56 +222,6 @@ public: ## 其他语言补充 - -### Python - -```python -class Solution: - def solveNQueens(self, n: int) -> List[List[str]]: - if not n: return [] - board = [['.'] * n for _ in range(n)] - res = [] - def isVaild(board,row, col): - #判断同一列是否冲突 - for i in range(len(board)): - if board[i][col] == 'Q': - return False - # 判断左上角是否冲突 - i = row -1 - j = col -1 - while i>=0 and j>=0: - if board[i][j] == 'Q': - return False - i -= 1 - j -= 1 - # 判断右上角是否冲突 - i = row - 1 - j = col + 1 - while i>=0 and j < len(board): - if board[i][j] == 'Q': - return False - i -= 1 - j += 1 - return True - - def backtracking(board, row, n): - # 如果走到最后一行,说明已经找到一个解 - if row == n: - temp_res = [] - for temp in board: - temp_str = "".join(temp) - temp_res.append(temp_str) - res.append(temp_res) - for col in range(n): - if not isVaild(board, row, col): - continue - board[row][col] = 'Q' - backtracking(board, row+1, n) - board[row][col] = '.' - backtracking(board, 0, n) - return res -``` - ### Java ```java @@ -341,6 +291,55 @@ class Solution { } ``` +### Python + +```python +class Solution: + def solveNQueens(self, n: int) -> List[List[str]]: + if not n: return [] + board = [['.'] * n for _ in range(n)] + res = [] + def isVaild(board,row, col): + #判断同一列是否冲突 + for i in range(len(board)): + if board[i][col] == 'Q': + return False + # 判断左上角是否冲突 + i = row -1 + j = col -1 + while i>=0 and j>=0: + if board[i][j] == 'Q': + return False + i -= 1 + j -= 1 + # 判断右上角是否冲突 + i = row - 1 + j = col + 1 + while i>=0 and j < len(board): + if board[i][j] == 'Q': + return False + i -= 1 + j += 1 + return True + + def backtracking(board, row, n): + # 如果走到最后一行,说明已经找到一个解 + if row == n: + temp_res = [] + for temp in board: + temp_str = "".join(temp) + temp_res.append(temp_str) + res.append(temp_res) + for col in range(n): + if not isVaild(board, row, col): + continue + board[row][col] = 'Q' + backtracking(board, row+1, n) + board[row][col] = '.' + backtracking(board, 0, n) + return res +``` + ### Go ```Go @@ -396,6 +395,8 @@ func isValid(n, row, col int, chessboard [][]string) bool { return true } ``` + + ### Javascript ```Javascript var solveNQueens = function(n) { diff --git a/problems/0070.爬楼梯完全背包版本.md b/problems/0070.爬楼梯完全背包版本.md index ec019e57..28439e09 100644 --- a/problems/0070.爬楼梯完全背包版本.md +++ b/problems/0070.爬楼梯完全背包版本.md @@ -187,12 +187,14 @@ func climbStairs(n int) int { JavaScript: ```javascript var climbStairs = function(n) { - const dp = new Array(n+1).fill(0); - const weight = [1,2]; + const dp = new Array(n + 1).fill(0); + const m = 2; dp[0] = 1; - for(let i = 0; i <= n; i++){ //先遍历背包 - for(let j = 0; j < weight.length; j++){ // 再遍历物品 - if(i >= weight[j]) dp[i] += dp[i-weight[j]]; + for(let i = 1; i <= n; i++){ + for(let j = 1; j <= m; j++){ + if(i >= j) { + dp[i] += dp[i - j]; + } } } return dp[n]; diff --git a/problems/0077.组合优化.md b/problems/0077.组合优化.md index e336fb75..b8b5f3c1 100644 --- a/problems/0077.组合优化.md +++ b/problems/0077.组合优化.md @@ -20,7 +20,7 @@ 大家先回忆一下[77. 组合]给出的回溯法的代码: -```c++ +```CPP class Solution { private: vector> result; // 存放符合条件结果的集合 @@ -52,7 +52,7 @@ public: 在遍历的过程中有如下代码: -```c++ +```CPP for (int i = startIndex; i <= n; i++) { path.push_back(i); backtracking(n, k, i + 1); @@ -76,7 +76,7 @@ for (int i = startIndex; i <= n; i++) { **如果for循环选择的起始位置之后的元素个数 已经不足 我们需要的元素个数了,那么就没有必要搜索了**。 注意代码中i,就是for循环里选择的起始位置。 -```c++ +```CPP for (int i = startIndex; i <= n; i++) { ``` @@ -98,13 +98,13 @@ for (int i = startIndex; i <= n; i++) { 所以优化之后的for循环是: -```c++ +```CPP for (int i = startIndex; i <= n - (k - path.size()) + 1; i++) // i为本次搜索的起始位置 ``` 优化后整体代码如下: -```c++ +```CPP class Solution { private: vector> result; diff --git a/problems/0332.重新安排行程.md b/problems/0332.重新安排行程.md index 8b5f797d..604d0261 100644 --- a/problems/0332.重新安排行程.md +++ b/problems/0332.重新安排行程.md @@ -261,6 +261,43 @@ for (pairtarget : targets[result[result.size() - 1]]) ## 其他语言版本 ### java + +```java +class Solution { + private LinkedList res; + private LinkedList path = new LinkedList<>(); + + public List findItinerary(List> tickets) { + Collections.sort(tickets, (a, b) -> a.get(1).compareTo(b.get(1))); + path.add("JFK"); + boolean[] used = new boolean[tickets.size()]; + backTracking((ArrayList) tickets, used); + return res; + } + + public boolean backTracking(ArrayList> tickets, boolean[] used) { + if (path.size() == tickets.size() + 1) { + res = new LinkedList(path); + return true; + } + + for (int i = 0; i < tickets.size(); i++) { + if (!used[i] && tickets.get(i).get(0).equals(path.getLast())) { + path.add(tickets.get(i).get(1)); + used[i] = true; + + if (backTracking(tickets, used)) { + return true; + } + + used[i] = false; + path.removeLast(); + } + } + return false; + } +} +``` ```java class Solution { diff --git a/problems/0347.前K个高频元素.md b/problems/0347.前K个高频元素.md index d4059b9b..a7049ae6 100644 --- a/problems/0347.前K个高频元素.md +++ b/problems/0347.前K个高频元素.md @@ -268,99 +268,102 @@ func topKFrequent(nums []int, k int) []int { -javaScript: +JavaScript: ```js -/** - * @param {number[]} nums - * @param {number} k - * @return {number[]} - */ -var topKFrequent = function(nums, k) { - const map = new Map(); - - for(const num of nums) { - map.set(num, (map.get(num) || 0) + 1); - } - - // 创建小顶堆 - const priorityQueue = new PriorityQueue((a, b) => a[1] - b[1]); - - // entry 是一个长度为2的数组,0位置存储key,1位置存储value - for (const entry of map.entries()) { - priorityQueue.push(entry); - if (priorityQueue.size() > k) { - priorityQueue.pop(); +// js 没有堆 需要自己构造 +class Heap { + constructor(compareFn) { + this.compareFn = compareFn; + this.queue = []; } - } - const ret = []; + // 添加 + push(item) { + // 推入元素 + this.queue.push(item); - for(let i = priorityQueue.size() - 1; i >= 0; i--) { - ret[i] = priorityQueue.pop()[0]; - } + // 上浮 + let index = this.size() - 1; // 记录推入元素下标 + let parent = Math.floor((index - 1) / 2); // 记录父节点下标 - return ret; + while (parent >= 0 && this.compare(parent, index) > 0) { // 注意compare参数顺序 + [this.queue[index], this.queue[parent]] = [this.queue[parent], this.queue[index]]; + + // 更新下标 + index = parent; + parent = Math.floor((index - 1) / 2); + } + } + + // 获取堆顶元素并移除 + pop() { + // 堆顶元素 + const out = this.queue[0]; + + // 移除堆顶元素 填入最后一个元素 + this.queue[0] = this.queue.pop(); + + // 下沉 + let index = 0; // 记录下沉元素下标 + let left = 1; // left 是左子节点下标 left + 1 则是右子节点下标 + let searchChild = this.compare(left, left + 1) > 0 ? left + 1 : left; + + while (searchChild !== undefined && this.compare(index, searchChild) > 0) { // 注意compare参数顺序 + [this.queue[index], this.queue[searchChild]] = [this.queue[searchChild], this.queue[index]]; + + // 更新下标 + index = searchChild; + left = 2 * index + 1; + searchChild = this.compare(left, left + 1) > 0 ? left + 1 : left; + } + + return out; + } + + size() { + return this.queue.length; + } + + // 使用传入的 compareFn 比较两个位置的元素 + compare(index1, index2) { + // 处理下标越界问题 + if (this.queue[index1] === undefined) return 1; + if (this.queue[index2] === undefined) return -1; + + return this.compareFn(this.queue[index1], this.queue[index2]); + } + +} + +const topKFrequent = function (nums, k) { + const map = new Map(); + + for (const num of nums) { + map.set(num, (map.get(num) || 0) + 1); + } + + // 创建小顶堆 + const heap= new Heap((a, b) => a[1] - b[1]); + + // entry 是一个长度为2的数组,0位置存储key,1位置存储value + for (const entry of map.entries()) { + heap.push(entry); + + if (heap.size() > k) { + heap.pop(); + } + } + + // return heap.queue.map(e => e[0]); + + const res = []; + + for (let i = heap.size() - 1; i >= 0; i--) { + res[i] = heap.pop()[0]; + } + + return res; }; - - -function PriorityQueue(compareFn) { - this.compareFn = compareFn; - this.queue = []; -} - -// 添加 -PriorityQueue.prototype.push = function(item) { - this.queue.push(item); - let index = this.queue.length - 1; - let parent = Math.floor((index - 1) / 2); - // 上浮 - while(parent >= 0 && this.compare(parent, index) > 0) { - // 交换 - [this.queue[index], this.queue[parent]] = [this.queue[parent], this.queue[index]]; - index = parent; - parent = Math.floor((index - 1) / 2); - } -} - -// 获取堆顶元素并移除 -PriorityQueue.prototype.pop = function() { - const ret = this.queue[0]; - - // 把最后一个节点移到堆顶 - this.queue[0] = this.queue.pop(); - - let index = 0; - // 左子节点下标,left + 1 就是右子节点下标 - let left = 1; - let selectedChild = this.compare(left, left + 1) > 0 ? left + 1 : left; - - // 下沉 - while(selectedChild !== undefined && this.compare(index, selectedChild) > 0) { - // 交换 - [this.queue[index], this.queue[selectedChild]] = [this.queue[selectedChild], this.queue[index]]; - index = selectedChild; - left = 2 * index + 1; - selectedChild = this.compare(left, left + 1) > 0 ? left + 1 : left; - } - - return ret; -} - -PriorityQueue.prototype.size = function() { - return this.queue.length; -} - -// 使用传入的 compareFn 比较两个位置的元素 -PriorityQueue.prototype.compare = function(index1, index2) { - if (this.queue[index1] === undefined) { - return 1; - } - if (this.queue[index2] === undefined) { - return -1; - } - - return this.compareFn(this.queue[index1], this.queue[index2]); -} ``` TypeScript: diff --git a/problems/0463.岛屿的周长.md b/problems/0463.岛屿的周长.md index ea038140..3dc69f20 100644 --- a/problems/0463.岛屿的周长.md +++ b/problems/0463.岛屿的周长.md @@ -118,6 +118,27 @@ class Solution { return res; } } + +// 解法二 +class Solution { + public int islandPerimeter(int[][] grid) { + // 计算岛屿的周长 + // 方法二 : 遇到相邻的陆地总周长就-2 + int landSum = 0; // 陆地数量 + int cover = 0; // 相邻陆地数量 + for (int i = 0; i < grid.length; i++) { + for (int j = 0; j < grid[0].length; j++) { + if (grid[i][j] == 1) { + landSum++; + // 统计上面和左边的相邻陆地 + if(i - 1 >= 0 && grid[i-1][j] == 1) cover++; + if(j - 1 >= 0 && grid[i][j-1] == 1) cover++; + } + } + } + return landSum * 4 - cover * 2; + } +} ``` Python: diff --git a/problems/0541.反转字符串II.md b/problems/0541.反转字符串II.md index 26d0b89c..80692c0b 100644 --- a/problems/0541.反转字符串II.md +++ b/problems/0541.反转字符串II.md @@ -12,7 +12,7 @@ [力扣题目链接](https://leetcode.cn/problems/reverse-string-ii/) -给定一个字符串 s 和一个整数 k,你需要对从字符串开头算起的每隔 2k 个字符的前 k 个字符进行反转。 +给定一个字符串 s 和一个整数 k,从字符串开头算起, 每计数至 2k 个字符,就反转这 2k 个字符中的前 k 个字符。 如果剩余字符少于 k 个,则将剩余字符全部反转。 diff --git a/problems/0707.设计链表.md b/problems/0707.设计链表.md index 00886039..42912eda 100644 --- a/problems/0707.设计链表.md +++ b/problems/0707.设计链表.md @@ -353,8 +353,12 @@ class MyLinkedList { return; } size--; + if (index == 0) { + head = head.next; + return; + } ListNode pred = head; - for (int i = 0; i < index; i++) { + for (int i = 0; i < index - 1; i++) { pred = pred.next; } pred.next = pred.next.next;