基础知识
- 数组下标从零开始
- 数组元素在内存中连续
- C++基础语法
//vector
#include <vector>
vector<int> vec;
vec.size();
vec.push_back(1);
//res(10,-1): 10 elements with all -1
vector<vector<int>> res(n, vector<int>(n, 0));
sort(res.begin(), res.end());
二分查找-704
Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to search `target` in `nums`.
If `target` exists, then return its index. Otherwise, return `-1`.
You must write an algorithm with `O(log n)` runtime complexity.
要点:
- 定义好左闭右开的区间,这个区间是循环不变量
错误:
- 确定中间元素序号时计算错误
- 一行一行阅读代码,避免思路正确但是书写错误
移除元素-27
Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return *the number of elements in* `nums` *which are not equal to* `val`.
Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things:
- Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`.
- Return `k`.
要点:
- 双指针法
长度最小的子数组-209 (need to be retested)
Given an array of positive integers `nums` and a positive integer `target`, return *the **minimal length** of a*
*subarray*
*whose sum is greater than or equal to* `target`. If there is no such subarray, return `0` instead.
要点:
- 确定好两个循环,以及循环的不变量
- for: 遍历所有元素
- while:显示写出不变量
- 必须用注释来帮忙review代码
错误:
- 使用一个循环来解决问题
- 错误计算数组元素数量
- 初始化错误的最小length值
这个循环转懵了很多人-59 (need to be retested)
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order.
要点:
- 确定好循环以及边界条件
错误:
- 变量名字需要更详细:total_loop,cur_loop
- 四条边需要统一左闭右开或者左开右闭
- 长宽的初始值需要详细计算