1. 题目列表
- 两句话中的不常见单词(模拟hashmap)
- 螺旋矩阵 III(二维网格行走模拟)
- 可能的二分法(判断二分图,BFS染色法)
- 鸡蛋掉落(二维dp,或公式推导)
2. 两句话中的不常见单词
hashmap按条件查询单词。
代码:
class Solution {
public String[] uncommonFromSentences(String A, String B) {
List res = new ArrayList();
HashMap map1 = new HashMap();
HashMap map2 = new HashMap();
String[] s1 = A.split(" ");
String[] s2 = B.split(" ");
for (String s : s1){
// System.out.println(s);
if (map1.get(s) == null){
map1.put(s, 1);
}else{
map1.put(s, map1.get(s) + 1);
}
}
for (String s : s2){
if (map2.get(s) == null){
map2.put(s, 1);
}else{
map2.put(s, map2.get(s) + 1);
}
}
for (String s : s1){
if (map1.get(s) == 1 && map2.get(s) == null)
res.add(s);
}
for (String s : s2){
if (map2.get(s) == 1 && map1.get(s) == null)
res.add(s);
}
return res.toArray(new String[res.size()]);
}
}
3. 螺旋矩阵 III
定义移动的步长S,当前的方向direct,分情况讨论当前的方向。 步长的移动规律是每次移动两次相同的步长S后,S++。
代码:
class Solution {
public:
vector> spiralMatrixIII(int R, int C, int r0, int c0) {
int r = r0, c = c0, direct = 1, step = 1, prestep = 0;
int cnt = 1;
vector< vector > res;
vector init(2);
init[0] = r0, init[1] = c0;
res.push_back(init);
while (cnt < R * C){
vector coor(2);
if (direct == 1){
// 遍历的每一个步都需要判断是否是答案路径
for (int i = 1; i <= step; i++){
c++;
if (judge(r, c, R, C)){
coor[0] = r, coor[1] = c;
res.push_back(coor);
cnt++;
}
}
direct = 2;
}else if (direct == 2){
for (int i = 1; i <= step; i++){
r++;
if (judge(r, c, R, C)){
coor[0] = r, coor[1] = c;
res.push_back(coor);
cnt++;
}
}
direct = 3;
}else if (direct == 3){
for (int i = 1; i <= step; i++){
c--;
if (judge(r, c, R, C)){
coor[0] = r, coor[1] = c;
res.push_back(coor);
cnt++;
}
}
direct = 0;
}else if (direct == 0){
for (int i = 1; i <= step; i++){
r--;
if (judge(r, c, R, C)){
coor[0] = r, coor[1] = c;
res.push_back(coor);
cnt++;
}
}
direct = 1;
}
if (prestep == step){
step++;
}else{
prestep = step;
}
}
return res;
}
bool judge(int r, int c, int R, int C){
if (r < 0 || r >= R || c < 0 || c >= C)
return false;
else return true;
}
};
4. 可能的二分法
BFS染色法判断是否是二分图,如果存在相邻的结点颜色相同,则返回false,否则返回true。
代码:
class Solution {
public:
/*
BFS染色法判断是否是二分图,如果存在相邻的结点颜色相同,则返回false,否则返回true
*/
bool visited[2010];
int g[2010][2010], color[2010];
bool possibleBipartition(int N, vector>& dislikes) {
memset(visited, false, sizeof(visited));
memset(color, 0, sizeof(color));
fill(g[0], g[0] + 2010 * 2010, 0x7fffffff);
for (int i = 0; i < dislikes.size(); i++){
g[dislikes[i][0]][dislikes[i][1]] = g[dislikes[i][1]][dislikes[i][0]] = 1;
}
bool flag = true;
for (int i = 1; i <= N; i++){
if (!visited[i] && !BFS(i, 1, N)){
flag = false;
break;
}
}
return flag;
}
bool BFS(int s, int c, int n){
queue< pair > q;
q.push(make_pair(s, c));
visited[s] = true;
while (!q.empty()){
pair u = q.front();
q.pop();
color[u.first] = u.second;
for (int i = 1; i <= n; i++){
// 如果存在邻接点染色相同
if (g[u.first][i] == 0x7fffffff) continue;
if (color[i] == u.second) return false;
if (!visited[i]){
q.push(make_pair(i, -u.second)); // 染成相反的颜色
visited[i] = true;
}
}
}
return true;
}
};