文章目录
- 1.买卖股票的最佳时机No.121
- 2.跳跃游戏No.55
- 3.跳跃游戏IINo.45
- 4.划分字母区间No.763
1.买卖股票的最佳时机No.121
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int price : prices) {
if (price < minPrice) {
minPrice = price;
}
else {
maxProfit = Math.max(maxProfit, price - minPrice);
}
}
return maxProfit;
}
}
2.跳跃游戏No.55
class Solution {
public boolean canJump(int[] nums) {
int maxReach = 0;
for (int i = 0; i < nums.length; i++) {
if (i > maxReach) {
return false;
}
maxReach = Math.max(maxReach, i + nums[i]);
if (maxReach >= nums.length - 1) {
return true;
}
}
return false;
}
}
public boolean canJump(int[] nums) {
if(nums.length==1) return true;
int cover = 0;
for(int i = 0;i<=cover;i++){
cover = Math.max(cover,i+nums[i]);
if(cover>=nums.length-1){
return true;
}
}
return false;
}
3.跳跃游戏IINo.45
class Solution {
public int jump(int[] nums) {
int n = nums.length;
if (n == 1) return 0;
int jumps = 0;
int farthest = 0;
int currentEnd = 0;
for (int i = 0; i < n ; i++) {
farthest = Math.max(farthest, i + nums[i]);
if (i == currentEnd) {
jumps++;
currentEnd = farthest;
if (currentEnd >= n - 1) {
break;
}
}
}
return jumps;
}
}
public int jump(int[] nums) {
if(nums.length==1) return 0;
int curr = 0;
int next = 0;
int jump = 0;
for(int i = 0;i<nums.length;i++){
next = Math.max(next,i+nums[i]);
if(i==curr){
jump++;
curr = next;
if(curr>=nums.length-1) break;
}
}
return jump;
}
4.划分字母区间No.763
- 思路
- 统计每一个字符最后出现的位置
- 从头遍历字符,并更新字符的最远出现下标,如果找到字符最远出现位置下标和当前下标相等了,则找到了分割点
class Solution {
public List<Integer> partitionLabels(String s) {
int[] lastIndex = new int[26];
for (int i = 0; i < s.length(); i++) {
lastIndex[s.charAt(i) - 'a'] = i;
}
List<Integer> result = new ArrayList<>();
int currentEnd = 0;
int start = 0;
for (int i = 0; i < s.length(); i++) {
currentEnd = Math.max(currentEnd, lastIndex[s.charAt(i) - 'a']);
if (i == currentEnd) {
result.add(i - start + 1);
start = i + 1;
}
}
return result;
}
}