41. First Missing Positive
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
提示:通过for while swap将每个正数放到正确的位置,然后for循环return第一个不正确数的位置,都正确return size + 1。
答案:
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
for(int i = 0; i < n; i++){
while(nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i])
swap(nums[i], nums[nums[i] - 1]);
}
for(int i = 0; i < n; i++){
if(nums[i] != i + 1)
return i + 1;
}
return n + 1;
}
};
42. Trapping Rain Water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
提示:
答案:
int trap(vector<int>& height) {
int l = 0, r = height.size()-1, level = 0, water = 0;
while (l < r) {
int lower = height[height[l] < height[r] ? l++ : r--];
level = max(level, lower);
water += level - lower;
}
return water;
}
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Example 1:
Input: [2,3,1,1,4] Output: true Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
提示:maxLocation 与 i + nums[i] 如果达不到 i return false
答案:
class Solution {
public:
bool canJump(vector<int>& nums) {
int maxLocation = 0;
for(int i = 0; i < nums.size(); i++){
if(maxLocation < i) return false;
maxLocation = i + nums[i] > maxLocation?i + nums[i]:maxLocation;
}
return true;
}
};
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example:
Input: [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
Note:
You can assume that you can always reach the last index.
提示:maxLocation 持续更新 当i 大于reach,更新reach
答案:
class Solution {
public:
int jump(vector<int>& nums) {
if(nums.size() < 2) return 0;
int step = 0, reach = 0, maxLocation = 0;
for(int i = 0; i < nums.size(); i++)
{
if(i > reach)
{
step++;
reach = maxLocation;//把持续更新的当下能一次到达的最远距离给reach;
if(reach >= nums.size() - 1)
return step;
}
maxLocation = max(maxLocation, nums[i] + i);
}
return step;
}
};
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix = [ [1,2,3], [4,5,6], [7,8,9] ], rotate the input matrix in-place such that it becomes: [ [7,4,1], [8,5,2], [9,6,3] ]
提示:
/*
* clockwise rotate
* first reverse up to down, then swap the symmetry
* 1 2 3 7 8 9 7 4 1
* 4 5 6 => 4 5 6 => 8 5 2
* 7 8 9 1 2 3 9 6 3*/
/*
* anticlockwise rotate
* first reverse left to right, then swap the symmetry
* 1 2 3 3 2 1 3 6 9
* 4 5 6 => 6 5 4 => 2 5 8
* 7 8 9 9 8 7 1 4 7
*/
答案:
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
reverse(matrix.begin(), matrix.end());
for(int i = 0; i < matrix.size(); i++){
for(int j = 0; j < i; j++){
swap(matrix[i][j], matrix[j][i]);
}
}
}
};
53. Maximum Subarray
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
提示:maxSoFar maxEndingHere
答案:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int maxSoFar = nums[0], maxEndingHere = nums[0];
for(int i = 1; i < nums.size(); i++){
maxEndingHere = max(maxEndingHere + nums[i], nums[i]);
maxSoFar = max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
};
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]
提示:方法一:直接按照顺序赋值,up right down left break
方法二:根据方向求解
答案:
方法一:
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.empty()) return {};
int m = matrix.size(), n = matrix[0].size();
vector<int> spiral(m * n);
int u = 0, d = m - 1, l = 0, r = n - 1, k = 0;
while(true){
//up
for(int col = l; col <= r; col++) spiral[k++] = matrix[u][col];
if(++u > d) break;
//right
for(int row = u; row <= d; row++) spiral[k++] = matrix[row][r];
if(--r < l) break;
//down
for(int col = r; col >= l; col--) spiral[k++] = matrix[d][col];
if(--d < u) break;
//left
for(int row = d; row >= u; row--) spiral[k++] = matrix[row][l];
if(++l > r) break;
}
return spiral;
}
};
方法二:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<vector<int> > dirs{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
vector<int> res;
int nr = matrix.size(); if (nr == 0) return res;
int nc = matrix[0].size(); if (nc == 0) return res;
vector<int> nSteps{nc, nr-1};
int iDir = 0; // index of direction.
int ir = 0, ic = -1; // initial position
while (nSteps[iDir%2]) {
for (int i = 0; i < nSteps[iDir%2]; ++i) {
ir += dirs[iDir][0]; ic += dirs[iDir][1];
res.push_back(matrix[ir][ic]);
}
nSteps[iDir%2]--;
iDir = (iDir + 1) % 4;
}
return res;
}
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
答案:
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > ret( n, vector<int>(n) );
int k = 1, i = 0;
while( k <= n * n )
{
int j = i;
// four steps
while( j < n - i ) // 1. horizonal, left to right
ret[i][j++] = k++;
j = i + 1;
while( j < n - i ) // 2. vertical, top to bottom
ret[j++][n-i-1] = k++;
j = n - i - 2;
while( j > i ) // 3. horizonal, right to left
ret[n-i-1][j--] = k++;
j = n - i - 1;
while( j > i ) // 4. vertical, bottom to top
ret[j--][i] = k++;
i++; // next loop
}
return ret;
}
};
Given a collection of intervals, merge all overlapping intervals.
Example 1:
Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
提示:sort(begin,end,cmp) result.back().end与intervals[i].start比较
答案:
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
private:
static bool cmp(const Interval& a, const Interval& b){
return a.start < b.start;
}
public:
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> result;
if(intervals.empty()) return result;
sort(intervals.begin(), intervals.end(),cmp);
result.push_back(intervals[0]);
for(int i = 1; i < intervals.size(); i++){
if(result.back().end >= intervals[i].start)
result.back().end = max(result.back().end, intervals[i].end);
else
result.push_back(intervals[i]);
}
return result;
}
};
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]]
提示:1.根据start找到合适位置 2. 比较pre.end 与insert.start 3.比较ans.end与后面的 i.start
答案:
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
/**
* @param intervals: Sorted interval list.
* @param newInterval: new interval.
* @return: A new interval list.
*/
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
// write your code here
vector<Interval> ans;
int st;
for(st = 0; st < intervals.size() && intervals[st].start < newInterval.start; st++){
ans.push_back(intervals[st]);
}
if(!ans.empty() && ans.back().end >= newInterval.start){
ans.back().end = max(ans.back().end, newInterval.end);
}else{
ans.push_back(newInterval);
}
for(int i = st; i < intervals.size(); i++){
if(ans.back().end >= intervals[i].start){
ans.back().end = max(ans.back().end, intervals[i].end);
}else{
ans.push_back(intervals[i]);
}
}
return ans;
}
};