leetcode做题
简单题开场
290. 单词规律
class Solution { public boolean wordPattern(String pattern, String s) { String[] words = s.split(" "); Map<Character, String> pToS = new HashMap<>(); Map<String, Character> sToP = new HashMap<>(); if(words.length != pattern.length()) return false; for(int i = 0; i < pattern.length(); i++){ char c = pattern.charAt(i); if((pToS.containsKey(c) && (!pToS.get(c).equals(words[i]))) || (sToP.containsKey(words[i]) && sToP.get(words[i]) != c) ){ return false; } pToS.put(c, words[i]); sToP.put(words[i], c); } return true; } }36. 有效的数独
自己做的时候是行,列,九宫分开写的,看题解才知道可以三合一的写
class Solution { public boolean isValidSudoku(char[][] board) { //三合一 开出三个数组 int[][] rowHas = new int[9][9]; //rowhas[i][j]表示第i行有数字j int[][] colHas = new int[9][9]; //colhas[i][j]表示第i列有数字j int[][][] subBoxHas = new int[3][3][9]; //subBoxHas[i][j][x] 表示 第i,j个九宫格有数字x for(int i = 0; i < 9; i++){ for(int j = 0; j < 9; j++){ char c = board[i][j]; if(c == '.') continue; //将数字1~9 转为 0 ~ 8 int temp = c - '0' - 1; rowHas[i][temp]++; colHas[j][temp]++; subBoxHas[i / 3][j / 3][temp]++; if(rowHas[i][temp] > 1 || colHas[j][temp] > 1 || subBoxHas[i / 3][j / 3][temp] > 1){ return false; } } } return true; } }54. 螺旋矩阵
以前在洛谷上做过,没想到还是不会
class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> ans = new ArrayList<>(); int n = matrix.length, m = matrix[0].length; int left = 0, right = m - 1, top = 0, bottom = n - 1; while(ans.size() < m * n){ for(int j = left; j <= right && ans.size() < m * n; j++){ ans.add( matrix[top][j] ); } top++; for(int i = top; i <= bottom && ans.size() < m * n; i++){ ans.add( matrix[i][right] ); } right--; for(int j = right; j >= left && ans.size() < m * n; j--){ ans.add( matrix[bottom][j] ); } bottom--; for(int i = bottom; i >= top && ans.size() < m * n; i--){ ans.add( matrix[i][left] ); } left++; } return ans; } }