9.Hash Table
1.Valid Sudoku
public class Solution {
public boolean isValidSudoku(char[][] board) {
for (int i = 0; i < 9; i++) {
HashSet<Character> rows = new HashSet<>();
HashSet<Character> columns = new HashSet<>();
HashSet<Character> cubes = new HashSet<>();
for (int j = 0; j < 9; j++) {
//row不满足条件
if(board[i][j]!='.'&&!rows.add(board[i][j])){
return false;
}
//column不满足条件
if(board[j][i]!='.'&&!columns.add(board[j][i])){
return false;
}
//定义每个cube最左上坐标
int rowIndex = 3*(i/3);//产生0,3,6
int columnIndex = 3*(i%3);//产生0,3,6
if(board[rowIndex+j/3][columnIndex+j%3]!='.'&&!cubes.add(board[rowIndex+j/3][columnIndex+j%3])){
return false;
}
}
}
return true;
}
}
2.Group Anagrams
Given an array of strings, group anagrams together.
For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Return:
[
[“ate”, “eat”,”tea”],
[“nat”,”tan”],
[“bat”]
]
Note: All inputs will be in lower-case.
算法的重点是:anagrams之间的共同点是sort后array一样!
熟悉map的iteration,熟悉char[]与String之间的互换。
public class Solution {
public List<List<String>> groupAnagrams(String[] strs) {
List<List<String>> result = new ArrayList<>();
if(strs.length==0){
return result;
}
HashMap<String,List<String>> map = new HashMap<>();
for (int i = 0; i < strs.length; i++) {
String eachString = strs[i];
char[] charArray = eachString.toCharArray();
//anagrams的共同点是sort后array一样!
Arrays.sort(charArray);
//char[] to string
String sortedString = String.valueOf(charArray);
if(map.containsKey(sortedString)){
map.get(sortedString).add(eachString);
}else{
List<String> list = new ArrayList();
list.add(eachString);
map.put(sortedString,list);
}
}
//iterate for map
for(Map.Entry<String,List<String>> entry:map.entrySet()){
result.add(entry.getValue());
}
return result;
}
}
3.Sort Characters By Frequency
Given a string, sort it in decreasing order based on the frequency of characters.
主要思路:掌握hashmap等各类map的自定义排序,掌握Simple way to repeat a String in java。
public class Solution {
public String frequencySort(String s) {
Map<Character,Integer> map = new HashMap<>();
char[] charArray = s.toCharArray();
StringBuilder result = new StringBuilder("");
if(s.length()==0){
return result.toString();
}
for (int i = 0; i < charArray.length; i++) {
if(map.containsKey(charArray[i])){
map.put(charArray[i],map.get(charArray[i])+1);
}else{
map.put(charArray[i],1);
}
}
//参见http://www.cnblogs.com/chenssy/p/3264214.html,对hashmap的排序
List<Map.Entry<Character,Integer>> list = new ArrayList<Map.Entry<Character,Integer>>(map.entrySet());
//实现Comparator接口
Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
@Override
public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
return -(o1.getValue().compareTo(o2.getValue()));//降序排列
}
});
for(Map.Entry<Character,Integer> mapping:list){
//char[] to String
String key = String.valueOf(mapping.getKey());
//repeat string n times
String repeated = new String(new char[mapping.getValue()]).replace("\0", key);
result.append(repeated);
}
return result.toString();
}
}
4.Minimum Window Substring
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
For example,
S = “ADOBECODEBANC”
T = “ABC”
Minimum window is “BANC”.
Note:
If there is no such window in S that covers all characters in T, return the empty string “”.
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
public class Solution {
public String minWindow(String s, String t) {
HashMap<Character,Integer> map = new HashMap();
for(char c : s.toCharArray())
map.put(c,0);
for(char c : t.toCharArray())
{
if(map.containsKey(c))
map.put(c,map.get(c)+1);
else
return "";
}
int start =0, end=0, minStart=0,minLen = Integer.MAX_VALUE, counter = t.length();
while(end < s.length())
{
char c1 = s.charAt(end);
if(map.get(c1) > 0)
counter--;
map.put(c1,map.get(c1)-1);
end++;
//当找到第一个window时
while(counter == 0)
{
if(minLen > end-start)
{
minLen = end-start;
minStart = start;
}
char c2 = s.charAt(start);
map.put(c2, map.get(c2)+1);
if(map.get(c2) > 0)
counter++;
start++;
}
}
return minLen == Integer.MAX_VALUE ? "" : s.substring(minStart,minStart+minLen);
}
}
通过运行程序设断点来厘清程序实现。
Discuss中一个大神写的关于substring的通用解决模板。上述代码是该模板的JAVA版本。
5.Max Points on a Line
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
思路一:
/**
* Definition for a point.
* class Point {
* int x;
* int y;
* Point() { x = 0; y = 0; }
* Point(int a, int b) { x = a; y = b; }
* }
*/
//success 1
//map存储斜率,处理边界条件为:1.重合点2.斜率为正无穷,即相同横坐标的情况
//但是map的key存储Double进行比较不安全,具体讲解:
//http://stackoverflow.com/questions/1074781/double-in-hashmap
public class Solution {
public int maxPoints(Point[] points) {
if(points.length <= 0) return 0;
if(points.length <= 2) return points.length;
int result = 0;
for(int i = 0; i < points.length; i++){
HashMap<Double, Integer> hm = new HashMap<Double, Integer>();
int samex = 1;
int samep = 0;
for(int j = 0; j < points.length; j++){
if(j != i){
if((points[j].x == points[i].x) && (points[j].y == points[i].y)){
samep++;
}
if(points[j].x == points[i].x){
samex++;
continue;
}
double k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);
if(hm.containsKey(k)){
hm.put(k,hm.get(k) + 1);
}else{
hm.put(k, 2);
}
result = Math.max(result, hm.get(k) + samep);
}
}
result = Math.max(result, samex);
}
return result;
}
}
思路二:
//success 2
//通过两个Integer来对Double比较进行优化
public class Solution{
public int maxPoints(Point[] points) {
if (points==null) return 0;
if (points.length<=2) return points.length;
Map<Integer,Map<Integer,Integer>> map = new HashMap<Integer,Map<Integer,Integer>>();
int result=0;
for (int i=0;i<points.length;i++){
map.clear();
int overlap=0,max=0;
for (int j=i+1;j<points.length;j++){
int x=points[j].x-points[i].x;
int y=points[j].y-points[i].y;
if (x==0&&y==0){
overlap++;
continue;
}
int gcd=generateGCD(x,y);
if (gcd!=0){
x/=gcd;
y/=gcd;
}
if (map.containsKey(x)){
if (map.get(x).containsKey(y)){
map.get(x).put(y, map.get(x).get(y)+1);
}else{
map.get(x).put(y, 1);
}
}else{
Map<Integer,Integer> m = new HashMap<Integer,Integer>();
m.put(y, 1);
map.put(x, m);
}
max=Math.max(max, map.get(x).get(y));
}
result=Math.max(result, max+overlap+1);
}
return result;
}
private int generateGCD(int a,int b){
if (b==0) return a;
else return generateGCD(b,a%b);
}
}