mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
Merge branch 'youngyangyang04:master' into master
This commit is contained in:
@ -134,12 +134,13 @@ public int[] twoSum(int[] nums, int target) {
|
|||||||
}
|
}
|
||||||
Map<Integer, Integer> map = new HashMap<>();
|
Map<Integer, Integer> map = new HashMap<>();
|
||||||
for(int i = 0; i < nums.length; i++){
|
for(int i = 0; i < nums.length; i++){
|
||||||
int temp = target - nums[i];
|
int temp = target - nums[i]; // 遍历当前元素,并在map中寻找是否有匹配的key
|
||||||
if(map.containsKey(temp)){
|
if(map.containsKey(temp)){
|
||||||
res[1] = i;
|
res[1] = i;
|
||||||
res[0] = map.get(temp);
|
res[0] = map.get(temp);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
map.put(nums[i], i);
|
map.put(nums[i], i); // 如果没找到匹配对,就把访问过的元素和下标加入到map中
|
||||||
}
|
}
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
@ -153,15 +154,16 @@ class Solution:
|
|||||||
records = dict()
|
records = dict()
|
||||||
|
|
||||||
for index, value in enumerate(nums):
|
for index, value in enumerate(nums):
|
||||||
if target - value in records:
|
if target - value in records: # 遍历当前元素,并在map中寻找是否有匹配的key
|
||||||
return [records[target- value], index]
|
return [records[target- value], index]
|
||||||
records[value] = index
|
records[value] = index # 遍历当前元素,并在map中寻找是否有匹配的key
|
||||||
return []
|
return []
|
||||||
```
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
|
// 暴力解法
|
||||||
func twoSum(nums []int, target int) []int {
|
func twoSum(nums []int, target int) []int {
|
||||||
for k1, _ := range nums {
|
for k1, _ := range nums {
|
||||||
for k2 := k1 + 1; k2 < len(nums); k2++ {
|
for k2 := k1 + 1; k2 < len(nums); k2++ {
|
||||||
@ -216,11 +218,11 @@ Javascript
|
|||||||
```javascript
|
```javascript
|
||||||
var twoSum = function (nums, target) {
|
var twoSum = function (nums, target) {
|
||||||
let hash = {};
|
let hash = {};
|
||||||
for (let i = 0; i < nums.length; i++) {
|
for (let i = 0; i < nums.length; i++) { // 遍历当前元素,并在map中寻找是否有匹配的key
|
||||||
if (hash[target - nums[i]] !== undefined) {
|
if (hash[target - nums[i]] !== undefined) {
|
||||||
return [i, hash[target - nums[i]]];
|
return [i, hash[target - nums[i]]];
|
||||||
}
|
}
|
||||||
hash[nums[i]] = i;
|
hash[nums[i]] = i; // 如果没找到匹配对,就把访问过的元素和下标加入到map中
|
||||||
}
|
}
|
||||||
return [];
|
return [];
|
||||||
};
|
};
|
||||||
|
@ -253,13 +253,15 @@ class Solution {
|
|||||||
public List<List<Integer>> threeSum(int[] nums) {
|
public List<List<Integer>> threeSum(int[] nums) {
|
||||||
List<List<Integer>> result = new ArrayList<>();
|
List<List<Integer>> result = new ArrayList<>();
|
||||||
Arrays.sort(nums);
|
Arrays.sort(nums);
|
||||||
|
// 找出a + b + c = 0
|
||||||
|
// a = nums[i], b = nums[left], c = nums[right]
|
||||||
for (int i = 0; i < nums.length; i++) {
|
for (int i = 0; i < nums.length; i++) {
|
||||||
|
// 排序之后如果第一个元素已经大于零,那么无论如何组合都不可能凑成三元组,直接返回结果就可以了
|
||||||
if (nums[i] > 0) {
|
if (nums[i] > 0) {
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (i > 0 && nums[i] == nums[i - 1]) {
|
if (i > 0 && nums[i] == nums[i - 1]) { // 去重a
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -273,7 +275,7 @@ class Solution {
|
|||||||
left++;
|
left++;
|
||||||
} else {
|
} else {
|
||||||
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
|
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
|
||||||
|
// 去重逻辑应该放在找到一个三元组之后,对b 和 c去重
|
||||||
while (right > left && nums[right] == nums[right - 1]) right--;
|
while (right > left && nums[right] == nums[right - 1]) right--;
|
||||||
while (right > left && nums[left] == nums[left + 1]) left++;
|
while (right > left && nums[left] == nums[left + 1]) left++;
|
||||||
|
|
||||||
@ -294,12 +296,15 @@ class Solution:
|
|||||||
ans = []
|
ans = []
|
||||||
n = len(nums)
|
n = len(nums)
|
||||||
nums.sort()
|
nums.sort()
|
||||||
|
# 找出a + b + c = 0
|
||||||
|
# a = nums[i], b = nums[left], c = nums[right]
|
||||||
for i in range(n):
|
for i in range(n):
|
||||||
left = i + 1
|
left = i + 1
|
||||||
right = n - 1
|
right = n - 1
|
||||||
|
# 排序之后如果第一个元素已经大于零,那么无论如何组合都不可能凑成三元组,直接返回结果就可以了
|
||||||
if nums[i] > 0:
|
if nums[i] > 0:
|
||||||
break
|
break
|
||||||
if i >= 1 and nums[i] == nums[i - 1]:
|
if i >= 1 and nums[i] == nums[i - 1]: # 去重a
|
||||||
continue
|
continue
|
||||||
while left < right:
|
while left < right:
|
||||||
total = nums[i] + nums[left] + nums[right]
|
total = nums[i] + nums[left] + nums[right]
|
||||||
@ -309,13 +314,14 @@ class Solution:
|
|||||||
left += 1
|
left += 1
|
||||||
else:
|
else:
|
||||||
ans.append([nums[i], nums[left], nums[right]])
|
ans.append([nums[i], nums[left], nums[right]])
|
||||||
|
# 去重逻辑应该放在找到一个三元组之后,对b 和 c去重
|
||||||
while left != right and nums[left] == nums[left + 1]: left += 1
|
while left != right and nums[left] == nums[left + 1]: left += 1
|
||||||
while left != right and nums[right] == nums[right - 1]: right -= 1
|
while left != right and nums[right] == nums[right - 1]: right -= 1
|
||||||
left += 1
|
left += 1
|
||||||
right -= 1
|
right -= 1
|
||||||
return ans
|
return ans
|
||||||
```
|
```
|
||||||
Python (v2):
|
Python (v3):
|
||||||
|
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
@ -344,32 +350,36 @@ class Solution:
|
|||||||
Go:
|
Go:
|
||||||
|
|
||||||
```Go
|
```Go
|
||||||
func threeSum(nums []int)[][]int{
|
func threeSum(nums []int) [][]int {
|
||||||
sort.Ints(nums)
|
sort.Ints(nums)
|
||||||
res:=[][]int{}
|
res := [][]int{}
|
||||||
|
// 找出a + b + c = 0
|
||||||
for i:=0;i<len(nums)-2;i++{
|
// a = nums[i], b = nums[left], c = nums[right]
|
||||||
n1:=nums[i]
|
for i := 0; i < len(nums)-2; i++ {
|
||||||
if n1>0{
|
// 排序之后如果第一个元素已经大于零,那么无论如何组合都不可能凑成三元组,直接返回结果就可以了
|
||||||
|
n1 := nums[i]
|
||||||
|
if n1 > 0 {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
if i>0&&n1==nums[i-1]{
|
// 去重a
|
||||||
|
if i > 0 && n1 == nums[i-1] {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
l,r:=i+1,len(nums)-1
|
l, r := i+1, len(nums)-1
|
||||||
for l<r{
|
for l < r {
|
||||||
n2,n3:=nums[l],nums[r]
|
n2, n3 := nums[l], nums[r]
|
||||||
if n1+n2+n3==0{
|
if n1+n2+n3 == 0 {
|
||||||
res=append(res,[]int{n1,n2,n3})
|
res = append(res, []int{n1, n2, n3})
|
||||||
for l<r&&nums[l]==n2{
|
// 去重逻辑应该放在找到一个三元组之后,对b 和 c去重
|
||||||
|
for l < r && nums[l] == n2 {
|
||||||
l++
|
l++
|
||||||
}
|
}
|
||||||
for l<r&&nums[r]==n3{
|
for l < r && nums[r] == n3 {
|
||||||
r--
|
r--
|
||||||
}
|
}
|
||||||
}else if n1+n2+n3<0{
|
} else if n1+n2+n3 < 0 {
|
||||||
l++
|
l++
|
||||||
}else {
|
} else {
|
||||||
r--
|
r--
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -142,19 +142,20 @@ class Solution {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (i > 0 && nums[i - 1] == nums[i]) {
|
if (i > 0 && nums[i - 1] == nums[i]) { // 对nums[i]去重
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (int j = i + 1; j < nums.length; j++) {
|
for (int j = i + 1; j < nums.length; j++) {
|
||||||
|
|
||||||
if (j > i + 1 && nums[j - 1] == nums[j]) {
|
if (j > i + 1 && nums[j - 1] == nums[j]) { // 对nums[j]去重
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
int left = j + 1;
|
int left = j + 1;
|
||||||
int right = nums.length - 1;
|
int right = nums.length - 1;
|
||||||
while (right > left) {
|
while (right > left) {
|
||||||
|
// nums[k] + nums[i] + nums[left] + nums[right] > target int会溢出
|
||||||
long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
|
long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
|
||||||
if (sum > target) {
|
if (sum > target) {
|
||||||
right--;
|
right--;
|
||||||
@ -162,7 +163,7 @@ class Solution {
|
|||||||
left++;
|
left++;
|
||||||
} else {
|
} else {
|
||||||
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
|
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
|
||||||
|
// 对nums[left]和nums[right]去重
|
||||||
while (right > left && nums[right] == nums[right - 1]) right--;
|
while (right > left && nums[right] == nums[right - 1]) right--;
|
||||||
while (right > left && nums[left] == nums[left + 1]) left++;
|
while (right > left && nums[left] == nums[left + 1]) left++;
|
||||||
|
|
||||||
@ -187,9 +188,9 @@ class Solution:
|
|||||||
n = len(nums)
|
n = len(nums)
|
||||||
res = []
|
res = []
|
||||||
for i in range(n):
|
for i in range(n):
|
||||||
if i > 0 and nums[i] == nums[i - 1]: continue
|
if i > 0 and nums[i] == nums[i - 1]: continue # 对nums[i]去重
|
||||||
for k in range(i+1, n):
|
for k in range(i+1, n):
|
||||||
if k > i + 1 and nums[k] == nums[k-1]: continue
|
if k > i + 1 and nums[k] == nums[k-1]: continue # 对nums[k]去重
|
||||||
p = k + 1
|
p = k + 1
|
||||||
q = n - 1
|
q = n - 1
|
||||||
|
|
||||||
@ -198,6 +199,7 @@ class Solution:
|
|||||||
elif nums[i] + nums[k] + nums[p] + nums[q] < target: p += 1
|
elif nums[i] + nums[k] + nums[p] + nums[q] < target: p += 1
|
||||||
else:
|
else:
|
||||||
res.append([nums[i], nums[k], nums[p], nums[q]])
|
res.append([nums[i], nums[k], nums[p], nums[q]])
|
||||||
|
# 对nums[p]和nums[q]去重
|
||||||
while p < q and nums[p] == nums[p + 1]: p += 1
|
while p < q and nums[p] == nums[p + 1]: p += 1
|
||||||
while p < q and nums[q] == nums[q - 1]: q -= 1
|
while p < q and nums[q] == nums[q - 1]: q -= 1
|
||||||
p += 1
|
p += 1
|
||||||
@ -258,12 +260,12 @@ func fourSum(nums []int, target int) [][]int {
|
|||||||
// if n1 > target { // 不能这样写,因为可能是负数
|
// if n1 > target { // 不能这样写,因为可能是负数
|
||||||
// break
|
// break
|
||||||
// }
|
// }
|
||||||
if i > 0 && n1 == nums[i-1] {
|
if i > 0 && n1 == nums[i-1] { // 对nums[i]去重
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for j := i + 1; j < len(nums)-2; j++ {
|
for j := i + 1; j < len(nums)-2; j++ {
|
||||||
n2 := nums[j]
|
n2 := nums[j]
|
||||||
if j > i+1 && n2 == nums[j-1] {
|
if j > i+1 && n2 == nums[j-1] { // 对nums[j]去重
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
l := j + 1
|
l := j + 1
|
||||||
@ -320,6 +322,8 @@ var fourSum = function(nums, target) {
|
|||||||
if(sum < target) { l++; continue}
|
if(sum < target) { l++; continue}
|
||||||
if(sum > target) { r--; continue}
|
if(sum > target) { r--; continue}
|
||||||
res.push([nums[i], nums[j], nums[l], nums[r]]);
|
res.push([nums[i], nums[j], nums[l], nums[r]]);
|
||||||
|
|
||||||
|
// 对nums[left]和nums[right]去重
|
||||||
while(l < r && nums[l] === nums[++l]);
|
while(l < r && nums[l] === nums[++l]);
|
||||||
while(l < r && nums[r] === nums[--r]);
|
while(l < r && nums[r] === nums[--r]);
|
||||||
}
|
}
|
||||||
|
@ -119,6 +119,19 @@ class Solution:
|
|||||||
return False
|
return False
|
||||||
```
|
```
|
||||||
|
|
||||||
|
```python
|
||||||
|
## for循环
|
||||||
|
class Solution:
|
||||||
|
def canJump(self, nums: List[int]) -> bool:
|
||||||
|
cover = 0
|
||||||
|
if len(nums) == 1: return True
|
||||||
|
for i in range(len(nums)):
|
||||||
|
if i <= cover:
|
||||||
|
cover = max(i + nums[i], cover)
|
||||||
|
if cover >= len(nums) - 1: return True
|
||||||
|
return False
|
||||||
|
```
|
||||||
|
|
||||||
### Go
|
### Go
|
||||||
```Go
|
```Go
|
||||||
func canJUmp(nums []int) bool {
|
func canJUmp(nums []int) bool {
|
||||||
|
@ -310,6 +310,18 @@ class Solution:
|
|||||||
return dp[(length-1) % 2][1]
|
return dp[(length-1) % 2][1]
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> 动态规划:版本三
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def maxProfit(self, prices: List[int]) -> int:
|
||||||
|
length = len(prices)
|
||||||
|
dp0, dp1 = -prices[0], 0 #注意这里只维护两个常量,因为dp0的更新不受dp1的影响
|
||||||
|
for i in range(1, length):
|
||||||
|
dp1 = max(dp1, dp0 + prices[i])
|
||||||
|
dp0 = max(dp0, -prices[i])
|
||||||
|
return dp1
|
||||||
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
> 贪心法:
|
> 贪心法:
|
||||||
```Go
|
```Go
|
||||||
|
@ -857,6 +857,36 @@ object Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### rust
|
||||||
|
|
||||||
|
```rust
|
||||||
|
impl Solution {
|
||||||
|
//* 递归 */
|
||||||
|
pub fn invert_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
|
||||||
|
if let Some(node) = root.as_ref() {
|
||||||
|
let (left, right) = (node.borrow().left.clone(), node.borrow().right.clone());
|
||||||
|
node.borrow_mut().left = Self::invert_tree(right);
|
||||||
|
node.borrow_mut().right = Self::invert_tree(left);
|
||||||
|
}
|
||||||
|
root
|
||||||
|
}
|
||||||
|
//* 迭代 */
|
||||||
|
pub fn invert_tree(root: Option<Rc<RefCell<TreeNode>>>) -> Option<Rc<RefCell<TreeNode>>> {
|
||||||
|
let mut stack = vec![root.clone()];
|
||||||
|
while !stack.is_empty() {
|
||||||
|
if let Some(node) = stack.pop().unwrap() {
|
||||||
|
let (left, right) = (node.borrow().left.clone(), node.borrow().right.clone());
|
||||||
|
stack.push(right.clone());
|
||||||
|
stack.push(left.clone());
|
||||||
|
node.borrow_mut().left = right;
|
||||||
|
node.borrow_mut().right = left;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
root
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
|
@ -101,7 +101,7 @@ class Solution {
|
|||||||
int[] record = new int[26];
|
int[] record = new int[26];
|
||||||
|
|
||||||
for (int i = 0; i < s.length(); i++) {
|
for (int i = 0; i < s.length(); i++) {
|
||||||
record[s.charAt(i) - 'a']++;
|
record[s.charAt(i) - 'a']++; // 并不需要记住字符a的ASCII,只要求出一个相对数值就可以了
|
||||||
}
|
}
|
||||||
|
|
||||||
for (int i = 0; i < t.length(); i++) {
|
for (int i = 0; i < t.length(); i++) {
|
||||||
@ -109,11 +109,11 @@ class Solution {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (int count: record) {
|
for (int count: record) {
|
||||||
if (count != 0) {
|
if (count != 0) { // record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true; // record数组所有元素都为零0,说明字符串s和t是字母异位词
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@ -166,35 +166,10 @@ class Solution(object):
|
|||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
```go
|
|
||||||
func isAnagram(s string, t string) bool {
|
|
||||||
if len(s)!=len(t){
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
exists := make(map[byte]int)
|
|
||||||
for i:=0;i<len(s);i++{
|
|
||||||
if v,ok:=exists[s[i]];v>=0&&ok{
|
|
||||||
exists[s[i]]=v+1
|
|
||||||
}else{
|
|
||||||
exists[s[i]]=1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for i:=0;i<len(t);i++{
|
|
||||||
if v,ok:=exists[t[i]];v>=1&&ok{
|
|
||||||
exists[t[i]]=v-1
|
|
||||||
}else{
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Go写法二(没有使用slice作为哈希表,用数组来代替):
|
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func isAnagram(s string, t string) bool {
|
func isAnagram(s string, t string) bool {
|
||||||
record := [26]int{}
|
record := [26]int{}
|
||||||
|
|
||||||
for _, r := range s {
|
for _, r := range s {
|
||||||
record[r-rune('a')]++
|
record[r-rune('a')]++
|
||||||
}
|
}
|
||||||
@ -202,7 +177,7 @@ func isAnagram(s string, t string) bool {
|
|||||||
record[r-rune('a')]--
|
record[r-rune('a')]--
|
||||||
}
|
}
|
||||||
|
|
||||||
return record == [26]int{}
|
return record == [26]int{} // record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -151,6 +151,23 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 第二种方法用temp来交换数值更多人容易理解些
|
||||||
|
class Solution {
|
||||||
|
public void reverseString(char[] s) {
|
||||||
|
int l = 0;
|
||||||
|
int r = s.length - 1;
|
||||||
|
while(l < r){
|
||||||
|
char temp = s[l];
|
||||||
|
s[l] = s[r];
|
||||||
|
s[r] = temp;
|
||||||
|
l++;
|
||||||
|
r--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
@ -335,3 +352,4 @@ object Solution {
|
|||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
@ -147,32 +147,24 @@ Python3:
|
|||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
|
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
|
||||||
return list(set(nums1) & set(nums2)) # 两个数组先变成集合,求交集后还原为数组
|
val_dict = {}
|
||||||
|
ans = []
|
||||||
|
for num in nums1:
|
||||||
|
val_dict[num] = 1
|
||||||
|
|
||||||
|
for num in nums2:
|
||||||
|
if num in val_dict.keys() and val_dict[num] == 1:
|
||||||
|
ans.append(num)
|
||||||
|
val_dict[num] = 0
|
||||||
|
|
||||||
|
return ans
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
```go
|
```go
|
||||||
func intersection(nums1 []int, nums2 []int) []int {
|
func intersection(nums1 []int, nums2 []int) []int {
|
||||||
m := make(map[int]int)
|
set:=make(map[int]struct{},0) // 用map模拟set
|
||||||
for _, v := range nums1 {
|
|
||||||
m[v] = 1
|
|
||||||
}
|
|
||||||
var res []int
|
|
||||||
// 利用count>0,实现重复值只拿一次放入返回结果中
|
|
||||||
for _, v := range nums2 {
|
|
||||||
if count, ok := m[v]; ok && count > 0 {
|
|
||||||
res = append(res, v)
|
|
||||||
m[v]--
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
```
|
|
||||||
```golang
|
|
||||||
//优化版,利用set,减少count统计
|
|
||||||
func intersection(nums1 []int, nums2 []int) []int {
|
|
||||||
set:=make(map[int]struct{},0)
|
|
||||||
res:=make([]int,0)
|
res:=make([]int,0)
|
||||||
for _,v:=range nums1{
|
for _,v:=range nums1{
|
||||||
if _,ok:=set[v];!ok{
|
if _,ok:=set[v];!ok{
|
||||||
|
@ -264,6 +264,25 @@ class Solution:
|
|||||||
return max(dp[-1][0], dp[-1][1])
|
return max(dp[-1][0], dp[-1][1])
|
||||||
```
|
```
|
||||||
|
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def wiggleMaxLength(self, nums: List[int]) -> int:
|
||||||
|
# up i作为波峰最长的序列长度
|
||||||
|
# down i作为波谷最长的序列长度
|
||||||
|
n = len(nums)
|
||||||
|
# 长度为0和1的直接返回长度
|
||||||
|
if n<2: return n
|
||||||
|
for i in range(1,n):
|
||||||
|
if nums[i]>nums[i-1]:
|
||||||
|
# nums[i] 为波峰,1. 前面是波峰,up值不变,2. 前面是波谷,down值加1
|
||||||
|
# 目前up值取两者的较大值(其实down+1即可,可以推理前一步down和up最多相差1,所以down+1>=up)
|
||||||
|
up = max(up, down+1)
|
||||||
|
elif nums[i]<nums[i-1]:
|
||||||
|
# nums[i] 为波谷,1. 前面是波峰,up+1,2. 前面是波谷,down不变,取较大值
|
||||||
|
down = max(down, up+1)
|
||||||
|
return max(up, down)
|
||||||
|
```
|
||||||
|
|
||||||
### Go
|
### Go
|
||||||
|
|
||||||
**贪心**
|
**贪心**
|
||||||
|
@ -147,11 +147,11 @@ class Solution:
|
|||||||
|
|
||||||
arr = [0] * 26
|
arr = [0] * 26
|
||||||
|
|
||||||
for x in magazine:
|
for x in magazine: # 记录 magazine里各个字符出现次数
|
||||||
arr[ord(x) - ord('a')] += 1
|
arr[ord(x) - ord('a')] += 1
|
||||||
|
|
||||||
for x in ransomNote:
|
for x in ransomNote: # 在arr里对应的字符个数做--操作
|
||||||
if arr[ord(x) - ord('a')] == 0:
|
if arr[ord(x) - ord('a')] == 0: # 如果没有出现过直接返回
|
||||||
return False
|
return False
|
||||||
else:
|
else:
|
||||||
arr[ord(x) - ord('a')] -= 1
|
arr[ord(x) - ord('a')] -= 1
|
||||||
@ -234,12 +234,12 @@ Go:
|
|||||||
```go
|
```go
|
||||||
func canConstruct(ransomNote string, magazine string) bool {
|
func canConstruct(ransomNote string, magazine string) bool {
|
||||||
record := make([]int, 26)
|
record := make([]int, 26)
|
||||||
for _, v := range magazine {
|
for _, v := range magazine { // 通过recode数据记录 magazine里各个字符出现次数
|
||||||
record[v-'a']++
|
record[v-'a']++
|
||||||
}
|
}
|
||||||
for _, v := range ransomNote {
|
for _, v := range ransomNote { // 遍历ransomNote,在record里对应的字符个数做--操作
|
||||||
record[v-'a']--
|
record[v-'a']--
|
||||||
if record[v-'a'] < 0 {
|
if record[v-'a'] < 0 { // 如果小于零说明ransomNote里出现的字符,magazine没有
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -258,12 +258,12 @@ javaScript:
|
|||||||
var canConstruct = function(ransomNote, magazine) {
|
var canConstruct = function(ransomNote, magazine) {
|
||||||
const strArr = new Array(26).fill(0),
|
const strArr = new Array(26).fill(0),
|
||||||
base = "a".charCodeAt();
|
base = "a".charCodeAt();
|
||||||
for(const s of magazine) {
|
for(const s of magazine) { // 记录 magazine里各个字符出现次数
|
||||||
strArr[s.charCodeAt() - base]++;
|
strArr[s.charCodeAt() - base]++;
|
||||||
}
|
}
|
||||||
for(const s of ransomNote) {
|
for(const s of ransomNote) { // 对应的字符个数做--操作
|
||||||
const index = s.charCodeAt() - base;
|
const index = s.charCodeAt() - base;
|
||||||
if(!strArr[index]) return false;
|
if(!strArr[index]) return false; // 如果没记录过直接返回false
|
||||||
strArr[index]--;
|
strArr[index]--;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
|
@ -168,13 +168,15 @@ Go:
|
|||||||
|
|
||||||
```go
|
```go
|
||||||
func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) int {
|
func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) int {
|
||||||
m := make(map[int]int)
|
m := make(map[int]int) //key:a+b的数值,value:a+b数值出现的次数
|
||||||
count := 0
|
count := 0
|
||||||
|
// 遍历nums1和nums2数组,统计两个数组元素之和,和出现的次数,放到map中
|
||||||
for _, v1 := range nums1 {
|
for _, v1 := range nums1 {
|
||||||
for _, v2 := range nums2 {
|
for _, v2 := range nums2 {
|
||||||
m[v1+v2]++
|
m[v1+v2]++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 遍历nums3和nums4数组,找到如果 0-(c+d) 在map中出现过的话,就把map中key对应的value也就是出现次数统计出来
|
||||||
for _, v3 := range nums3 {
|
for _, v3 := range nums3 {
|
||||||
for _, v4 := range nums4 {
|
for _, v4 := range nums4 {
|
||||||
count += m[-v3-v4]
|
count += m[-v3-v4]
|
||||||
@ -197,14 +199,14 @@ javaScript:
|
|||||||
var fourSumCount = function(nums1, nums2, nums3, nums4) {
|
var fourSumCount = function(nums1, nums2, nums3, nums4) {
|
||||||
const twoSumMap = new Map();
|
const twoSumMap = new Map();
|
||||||
let count = 0;
|
let count = 0;
|
||||||
|
// 统计nums1和nums2数组元素之和,和出现的次数,放到map中
|
||||||
for(const n1 of nums1) {
|
for(const n1 of nums1) {
|
||||||
for(const n2 of nums2) {
|
for(const n2 of nums2) {
|
||||||
const sum = n1 + n2;
|
const sum = n1 + n2;
|
||||||
twoSumMap.set(sum, (twoSumMap.get(sum) || 0) + 1)
|
twoSumMap.set(sum, (twoSumMap.get(sum) || 0) + 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 找到如果 0-(c+d) 在map中出现过的话,就把map中key对应的value也就是出现次数统计出来
|
||||||
for(const n3 of nums3) {
|
for(const n3 of nums3) {
|
||||||
for(const n4 of nums4) {
|
for(const n4 of nums4) {
|
||||||
const sum = n3 + n4;
|
const sum = n3 + n4;
|
||||||
|
@ -194,6 +194,29 @@ class Solution {
|
|||||||
return new String(ch);
|
return new String(ch);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 解法二还可以用temp来交换数值,会的人更多些
|
||||||
|
class Solution {
|
||||||
|
public String reverseStr(String s, int k) {
|
||||||
|
char[] ch = s.toCharArray();
|
||||||
|
for(int i = 0;i < ch.length;i += 2 * k){
|
||||||
|
int start = i;
|
||||||
|
// 判断尾数够不够k个来取决end指针的位置
|
||||||
|
int end = Math.min(ch.length - 1,start + k - 1);
|
||||||
|
while(start < end){
|
||||||
|
|
||||||
|
char temp = ch[start];
|
||||||
|
ch[start] = ch[end];
|
||||||
|
ch[end] = temp;
|
||||||
|
|
||||||
|
start++;
|
||||||
|
end--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new String(ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
```java
|
```java
|
||||||
// 解法3
|
// 解法3
|
||||||
@ -469,3 +492,4 @@ impl Solution {
|
|||||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
@ -305,7 +305,7 @@ class MyLinkedList {
|
|||||||
head = new ListNode(0);
|
head = new ListNode(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
//获取第index个节点的数值
|
//获取第index个节点的数值,注意index是从0开始的,第0个节点就是头结点
|
||||||
public int get(int index) {
|
public int get(int index) {
|
||||||
//如果index非法,返回-1
|
//如果index非法,返回-1
|
||||||
if (index < 0 || index >= size) {
|
if (index < 0 || index >= size) {
|
||||||
@ -319,12 +319,12 @@ class MyLinkedList {
|
|||||||
return currentNode.val;
|
return currentNode.val;
|
||||||
}
|
}
|
||||||
|
|
||||||
//在链表最前面插入一个节点
|
//在链表最前面插入一个节点,等价于在第0个元素前添加
|
||||||
public void addAtHead(int val) {
|
public void addAtHead(int val) {
|
||||||
addAtIndex(0, val);
|
addAtIndex(0, val);
|
||||||
}
|
}
|
||||||
|
|
||||||
//在链表的最后插入一个节点
|
//在链表的最后插入一个节点,等价于在(末尾+1)个元素前添加
|
||||||
public void addAtTail(int val) {
|
public void addAtTail(int val) {
|
||||||
addAtIndex(size, val);
|
addAtIndex(size, val);
|
||||||
}
|
}
|
||||||
@ -481,75 +481,89 @@ class MyLinkedList {
|
|||||||
Python:
|
Python:
|
||||||
```python
|
```python
|
||||||
# 单链表
|
# 单链表
|
||||||
class Node:
|
class Node(object):
|
||||||
|
def __init__(self, x=0):
|
||||||
def __init__(self, val):
|
self.val = x
|
||||||
self.val = val
|
|
||||||
self.next = None
|
self.next = None
|
||||||
|
|
||||||
|
class MyLinkedList(object):
|
||||||
class MyLinkedList:
|
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._head = Node(0) # 虚拟头部节点
|
self.head = Node()
|
||||||
self._count = 0 # 添加的节点数
|
self.size = 0 # 设置一个链表长度的属性,便于后续操作,注意每次增和删的时候都要更新
|
||||||
|
|
||||||
def get(self, index: int) -> int:
|
def get(self, index):
|
||||||
"""
|
"""
|
||||||
Get the value of the index-th node in the linked list. If the index is invalid, return -1.
|
:type index: int
|
||||||
|
:rtype: int
|
||||||
"""
|
"""
|
||||||
if 0 <= index < self._count:
|
if index < 0 or index >= self.size:
|
||||||
node = self._head
|
|
||||||
for _ in range(index + 1):
|
|
||||||
node = node.next
|
|
||||||
return node.val
|
|
||||||
else:
|
|
||||||
return -1
|
return -1
|
||||||
|
cur = self.head.next
|
||||||
|
while(index):
|
||||||
|
cur = cur.next
|
||||||
|
index -= 1
|
||||||
|
return cur.val
|
||||||
|
|
||||||
def addAtHead(self, val: int) -> None:
|
def addAtHead(self, val):
|
||||||
"""
|
"""
|
||||||
Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
|
:type val: int
|
||||||
|
:rtype: None
|
||||||
"""
|
"""
|
||||||
self.addAtIndex(0, val)
|
new_node = Node(val)
|
||||||
|
new_node.next = self.head.next
|
||||||
|
self.head.next = new_node
|
||||||
|
self.size += 1
|
||||||
|
|
||||||
def addAtTail(self, val: int) -> None:
|
def addAtTail(self, val):
|
||||||
"""
|
"""
|
||||||
Append a node of value val to the last element of the linked list.
|
:type val: int
|
||||||
|
:rtype: None
|
||||||
"""
|
"""
|
||||||
self.addAtIndex(self._count, val)
|
new_node = Node(val)
|
||||||
|
cur = self.head
|
||||||
|
while(cur.next):
|
||||||
|
cur = cur.next
|
||||||
|
cur.next = new_node
|
||||||
|
self.size += 1
|
||||||
|
|
||||||
def addAtIndex(self, index: int, val: int) -> None:
|
def addAtIndex(self, index, val):
|
||||||
"""
|
"""
|
||||||
Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
|
:type index: int
|
||||||
|
:type val: int
|
||||||
|
:rtype: None
|
||||||
"""
|
"""
|
||||||
if index < 0:
|
if index < 0:
|
||||||
index = 0
|
self.addAtHead(val)
|
||||||
elif index > self._count:
|
return
|
||||||
|
elif index == self.size:
|
||||||
|
self.addAtTail(val)
|
||||||
|
return
|
||||||
|
elif index > self.size:
|
||||||
return
|
return
|
||||||
|
|
||||||
# 计数累加
|
node = Node(val)
|
||||||
self._count += 1
|
pre = self.head
|
||||||
|
while(index):
|
||||||
|
pre = pre.next
|
||||||
|
index -= 1
|
||||||
|
node.next = pre.next
|
||||||
|
pre.next = node
|
||||||
|
self.size += 1
|
||||||
|
|
||||||
add_node = Node(val)
|
def deleteAtIndex(self, index):
|
||||||
prev_node, current_node = None, self._head
|
|
||||||
for _ in range(index + 1):
|
|
||||||
prev_node, current_node = current_node, current_node.next
|
|
||||||
else:
|
|
||||||
prev_node.next, add_node.next = add_node, current_node
|
|
||||||
|
|
||||||
def deleteAtIndex(self, index: int) -> None:
|
|
||||||
"""
|
"""
|
||||||
Delete the index-th node in the linked list, if the index is valid.
|
:type index: int
|
||||||
|
:rtype: None
|
||||||
"""
|
"""
|
||||||
if 0 <= index < self._count:
|
if index < 0 or index >= self.size:
|
||||||
# 计数-1
|
return
|
||||||
self._count -= 1
|
pre = self.head
|
||||||
prev_node, current_node = None, self._head
|
while(index):
|
||||||
for _ in range(index + 1):
|
pre = pre.next
|
||||||
prev_node, current_node = current_node, current_node.next
|
index -= 1
|
||||||
else:
|
pre.next = pre.next.next
|
||||||
prev_node.next, current_node.next = current_node.next, None
|
self.size -= 1
|
||||||
|
|
||||||
|
|
||||||
# 双链表
|
# 双链表
|
||||||
# 相对于单链表, Node新增了prev属性
|
# 相对于单链表, Node新增了prev属性
|
||||||
|
@ -206,13 +206,13 @@ class Solution: # 贪心思路
|
|||||||
result = 0
|
result = 0
|
||||||
minPrice = prices[0]
|
minPrice = prices[0]
|
||||||
for i in range(1, len(prices)):
|
for i in range(1, len(prices)):
|
||||||
if prices[i] < minPrice:
|
if prices[i] < minPrice: # 此时有更低的价格,可以买入
|
||||||
minPrice = prices[i]
|
minPrice = prices[i]
|
||||||
elif prices[i] >= minPrice and prices[i] <= minPrice + fee:
|
elif prices[i] > (minPrice + fee): # 此时有利润,同时假买入高价的股票,看看是否继续盈利
|
||||||
continue
|
result += prices[i] - (minPrice + fee)
|
||||||
else:
|
|
||||||
result += prices[i] - minPrice - fee
|
|
||||||
minPrice = prices[i] - fee
|
minPrice = prices[i] - fee
|
||||||
|
else: # minPrice<= prices[i] <= minPrice + fee, 价格处于minPrice和minPrice+fee之间,不做操作
|
||||||
|
continue
|
||||||
return result
|
return result
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -155,23 +155,28 @@ public class Solution {
|
|||||||
|
|
||||||
class Solution:
|
class Solution:
|
||||||
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
|
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
|
||||||
"""
|
lenA, lenB = 0, 0
|
||||||
根据快慢法则,走的快的一定会追上走得慢的。
|
cur = headA
|
||||||
在这道题里,有的链表短,他走完了就去走另一条链表,我们可以理解为走的快的指针。
|
while cur: # 求链表A的长度
|
||||||
|
cur = cur.next
|
||||||
那么,只要其中一个链表走完了,就去走另一条链表的路。如果有交点,他们最终一定会在同一个
|
lenA += 1
|
||||||
位置相遇
|
cur = headB
|
||||||
"""
|
while cur: # 求链表B的长度
|
||||||
if headA is None or headB is None:
|
cur = cur.next
|
||||||
|
lenB += 1
|
||||||
|
curA, curB = headA, headB
|
||||||
|
if lenA > lenB: # 让curB为最长链表的头,lenB为其长度
|
||||||
|
curA, curB = curB, curA
|
||||||
|
lenA, lenB = lenB, lenA
|
||||||
|
for _ in range(lenB - lenA): # 让curA和curB在同一起点上(末尾位置对齐)
|
||||||
|
curB = curB.next
|
||||||
|
while curA: # 遍历curA 和 curB,遇到相同则直接返回
|
||||||
|
if curA == curB:
|
||||||
|
return curA
|
||||||
|
else:
|
||||||
|
curA = curA.next
|
||||||
|
curB = curB.next
|
||||||
return None
|
return None
|
||||||
cur_a, cur_b = headA, headB # 用两个指针代替a和b
|
|
||||||
|
|
||||||
|
|
||||||
while cur_a != cur_b:
|
|
||||||
cur_a = cur_a.next if cur_a else headB # 如果a走完了,那么就切换到b走
|
|
||||||
cur_b = cur_b.next if cur_b else headA # 同理,b走完了就切换到a
|
|
||||||
|
|
||||||
return cur_a
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Go
|
### Go
|
||||||
@ -248,19 +253,21 @@ var getListLen = function(head) {
|
|||||||
}
|
}
|
||||||
var getIntersectionNode = function(headA, headB) {
|
var getIntersectionNode = function(headA, headB) {
|
||||||
let curA = headA,curB = headB,
|
let curA = headA,curB = headB,
|
||||||
lenA = getListLen(headA),
|
lenA = getListLen(headA), // 求链表A的长度
|
||||||
lenB = getListLen(headB);
|
lenB = getListLen(headB);
|
||||||
if(lenA < lenB) {
|
if(lenA < lenB) { // 让curA为最长链表的头,lenA为其长度
|
||||||
// 下面交换变量注意加 “分号” ,两个数组交换变量在同一个作用域下时
|
|
||||||
|
// 交换变量注意加 “分号” ,两个数组交换变量在同一个作用域下时
|
||||||
// 如果不加分号,下面两条代码等同于一条代码: [curA, curB] = [lenB, lenA]
|
// 如果不加分号,下面两条代码等同于一条代码: [curA, curB] = [lenB, lenA]
|
||||||
|
|
||||||
[curA, curB] = [curB, curA];
|
[curA, curB] = [curB, curA];
|
||||||
[lenA, lenB] = [lenB, lenA];
|
[lenA, lenB] = [lenB, lenA];
|
||||||
}
|
}
|
||||||
let i = lenA - lenB;
|
let i = lenA - lenB; // 求长度差
|
||||||
while(i-- > 0) {
|
while(i-- > 0) { // 让curA和curB在同一起点上(末尾位置对齐)
|
||||||
curA = curA.next;
|
curA = curA.next;
|
||||||
}
|
}
|
||||||
while(curA && curA !== curB) {
|
while(curA && curA !== curB) { // 遍历curA 和 curB,遇到相同则直接返回
|
||||||
curA = curA.next;
|
curA = curA.next;
|
||||||
curB = curB.next;
|
curB = curB.next;
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user