Merge pull request #666 from ironartisan/master

添加0455.分发饼干代码
This commit is contained in:
程序员Carl
2021-08-28 11:55:26 +08:00
committed by GitHub
3 changed files with 66 additions and 9 deletions

View File

@ -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;
}
}
```

View File

@ -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
//排序后,局部最优

View File

@ -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: