哈希表
1.剑指offer 50(HashMap)
HashMap<Character, Boolean> dic = new HashMap<>();
char[] sc = s.toCharArray();
//若字符c出现第二次,再次put便是false
for(char c : sc)
dic.put(c, !dic.containsKey(c));
for(char c : sc)
//get方法取出键值c对应的内容(即对应的true/false)
if(dic.get(c)) return c;
return ' ';
HashMap的基本使用方法。
2. leetcode 1496. 判断路径是否相交(HashSet)
int x = 0, y = 0;
//HashSet不能存储重复元素
Set<String> set = new HashSet<>();
set.add(x + "," + y);
for (int i = 0; i < path.length(); i++){
char ch = path.charAt(i);
int next_x = 0, next_y = 0;
if (ch == 'N'){
next_x = x;
next_y = y + 1;
} else if (ch == 'S'){
next_x = x;
next_y = y - 1;
} else if (ch == 'E'){
next_x = x + 1;
next_y = y;
} else if (ch == 'W'){
next_x = x - 1;
next_y = y;
}
if (set.contains(next_x + "," + next_y)){
return true;
} else {
set.add(next_x + "," + next_y);
x = next_x;
y = next_y;
}
}
return false;
HashSet的特点
访问HashSet