# 2. 两句话中的不常见单词

hashmap按条件查询单词。

``````class Solution {
public String[] uncommonFromSentences(String A, String B) {
List<String> res = new ArrayList<String>();
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
HashMap<String, Integer> map2 = new HashMap<String, Integer>();
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)
}
for (String s : s2){
if (map2.get(s) == 1 && map1.get(s) == null)
}
return res.toArray(new String[res.size()]);
}
}
``````

# 3. 螺旋矩阵 III

``````class Solution {
public:

vector<vector<int>> 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<int> > res;
vector<int> init(2);
init[0] = r0, init[1] = c0;
res.push_back(init);
while (cnt < R * C){
vector<int> 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<vector<int>>& 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<int, int> > q;
q.push(make_pair(s, c));
visited[s] = true;
while (!q.empty()){
pair<int, int > 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;
}

};
``````