代码
class Solution {
public int minCostClimbingStairs(int[] cost) {
int n = cost.length;
int[] dp = new int[n+1];
dp[0] = 0;
dp[1] = 0;
for(int i = 2;i <= n;i++){
dp[i] = Math.min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]);
}
return dp[n];
}
}
class Solution {
public int minCostClimbingStairs(int[] cost) {
int dp1 = 0;
int dp2 = 0;
for(int i = 2;i <= cost.length;i++){
int dpi = Math.min(cost[i-1]+dp2,cost[i-2]+dp1);
dp1 = dp2;
dp2 = dpi;
}
return dp2;
}
}
分析
确定dp数组的含义
i
个台阶需要花费的价格为dp[i]确定递推公式
dp[i] = dp[i-1]+cost[i-1]
dp[i] = dp[i-2]+cost[i-2]
初始化dp
dp[0] = 0,dp[1]=0
解法二
cost
数组得来的,只需要记录一下前两位的值并且更新就行了。代码
class Solution {
public int findPeakElement(int[] nums) {
int maxIndex = 0;
for(int i = 1;i<nums.length;i++){
if(nums[i] > nums[maxIndex]){
maxIndex = i;
}
}
return maxIndex;
}
}
class Solution {
public int findPeakElement(int[] nums) {
int n = nums.length;
for(int i = 0;i < n;i++){
boolean ok = true;
if(i - 1 >= 0){
if(nums[i-1] >= nums[i]) ok = false;
}
if(i + 1 < n){
if(nums[i+1] >= nums[i]) ok = false;
}
if(ok) return i;
}
return -1;
}
}
class Solution {
public int findPeakElement(int[] nums) {
int l = 0;
int r = nums.length - 1;
while(l < r){
int mid = (l+r)/2;
if(nums[mid] < nums[mid+1]) l = mid + 1;
else r = mid;
}
return r;
}
}