mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
@ -139,17 +139,11 @@ Java:
|
||||
// 贪心思路
|
||||
class Solution {
|
||||
public int maxProfit(int[] prices) {
|
||||
int sum = 0;
|
||||
int profit = 0;
|
||||
int buy = prices[0];
|
||||
int result = 0;
|
||||
for (int i = 1; i < prices.length; i++) {
|
||||
profit = prices[i] - buy;
|
||||
if (profit > 0) {
|
||||
sum += profit;
|
||||
}
|
||||
buy = prices[i];
|
||||
result += Math.max(prices[i] - prices[i - 1], 0);
|
||||
}
|
||||
return sum;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -117,6 +117,7 @@ public:
|
||||
Java:
|
||||
```java
|
||||
class Solution {
|
||||
// 思路1:优先考虑饼干,小饼干先喂饱小胃口
|
||||
public int findContentChildren(int[] g, int[] s) {
|
||||
Arrays.sort(g);
|
||||
Arrays.sort(s);
|
||||
@ -132,10 +133,30 @@ class Solution {
|
||||
}
|
||||
}
|
||||
```
|
||||
```java
|
||||
class Solution {
|
||||
// 思路2:优先考虑胃口,先喂饱大胃口
|
||||
public int findContentChildren(int[] g, int[] s) {
|
||||
Arrays.sort(g);
|
||||
Arrays.sort(s);
|
||||
int count = 0;
|
||||
int start = s.length - 1;
|
||||
// 遍历胃口
|
||||
for (int index = g.length - 1; index >= 0; index--) {
|
||||
if(start >= 0 && g[index] <= s[start]) {
|
||||
start--;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Python:
|
||||
```python3
|
||||
class Solution:
|
||||
# 思路1:优先考虑胃饼干
|
||||
def findContentChildren(self, g: List[int], s: List[int]) -> int:
|
||||
g.sort()
|
||||
s.sort()
|
||||
@ -145,6 +166,20 @@ class Solution:
|
||||
res += 1
|
||||
return res
|
||||
```
|
||||
```python
|
||||
class Solution:
|
||||
# 思路2:优先考虑胃口
|
||||
def findContentChildren(self, g: List[int], s: List[int]) -> int:
|
||||
g.sort()
|
||||
s.sort()
|
||||
start, count = len(s) - 1, 0
|
||||
for index in range(len(g) - 1, -1, -1): # 先喂饱大胃口
|
||||
if start >= 0 and g[index] <= s[start]:
|
||||
start -= 1
|
||||
count += 1
|
||||
return count
|
||||
```
|
||||
|
||||
Go:
|
||||
```golang
|
||||
//排序后,局部最优
|
||||
|
@ -152,7 +152,35 @@ class Solution {
|
||||
}
|
||||
}
|
||||
```
|
||||
```java
|
||||
// 解法3
|
||||
class Solution {
|
||||
public String reverseStr(String s, int k) {
|
||||
char[] ch = s.toCharArray();
|
||||
// 1. 每隔 2k 个字符的前 k 个字符进行反转
|
||||
for (int i = 0; i< ch.length; i += 2 * k) {
|
||||
// 2. 剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符
|
||||
if (i + k <= ch.length) {
|
||||
reverse(ch, i, i + k -1);
|
||||
continue;
|
||||
}
|
||||
// 3. 剩余字符少于 k 个,则将剩余字符全部反转
|
||||
reverse(ch, i, ch.length - 1);
|
||||
}
|
||||
return new String(ch);
|
||||
|
||||
}
|
||||
// 定义翻转函数
|
||||
public void reverse(char[] ch, int i, int j) {
|
||||
for (; i < j; i++, j--) {
|
||||
char temp = ch[i];
|
||||
ch[i] = ch[j];
|
||||
ch[j] = temp;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
```
|
||||
Python:
|
||||
```python
|
||||
class Solution:
|
||||
|
Reference in New Issue
Block a user