35.Search Insert Position
Description:
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6]
, 5 → 2
[1,3,5,6]
, 2 → 1
[1,3,5,6]
, 7 → 4
[1,3,5,6]
, 0 → 0
My C++ code:
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int len = nums.size();
for(int i = 0;i < len;i++)
{
if(target <= nums[i])return i;
else if(i == len - 1)
return len;
}
}
};
70.Climbing Stairs
Description:
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
My C++ code:
class Solution {
public:
int solved[100] = {0};
int climbStairs(int n) {
if(n == 1)return 1;
else if(n == 2)return 2;
else
{
if(solved[n]) return solved[n];
else
{
int x = climbStairs(n-1) + climbStairs(n-2);
solved[n] = x;
return x;
}
}
}
};