publicintromanToInt(String s){ int ret = 0; String[] strArr = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"}; int[] num = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
HashMap<String, Integer> map = new HashMap<>(); for (int i = 0; i < strArr.length; i++) { map.put(strArr[i],num[i]); }
for (int i = 0; i < s.length();) { if (i+2<=s.length() && (map.containsKey(s.substring(i,i+2)))){ ret += map.get(s.substring(i,i+2)); i += 2; continue; } ret += map.get(s.substring(i,i+1)); i += 1; } return ret; }
public String largestNumber(int[] nums){ /// 不能用顺序排列 /// 数字排序和字符串排序思路都不同 int n = nums.length; String[] numStr = new String[n]; for (int i = 0; i < n; i++) { numStr[i] = String.valueOf(nums[i]); }
publicintdivingBoard(int shorter, int longer, int k){ if (k < 0)return0; if (k == 0)return1; return climb(shorter, longer, k - 1) + climb(shorter, longer, k - 2); }
非递归方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicint[] divingBoard(int shorter, int longer, int k) { if(k == 0){ returnnewint[0]; } elseif (shorter == longer){ int[] ret = {shorter * k}; return ret; } int[] board = newint[k + 1]; int shortest = k * shorter; for (int i = 0; i < k + 1; i++) { board[i] = shortest + i * (longer - shorter); } return board; }
publicvoidupdateBoardDfs(char[][] board, int x, int y, int[][] sign){ if (x >= height || x < 0 || y >= width || y < 0 || sign[x][y] == 1){ return; } // 首先判断周围8个方向是否有雷 getCountBomb(board, x, y); if (countBomb != 0){ board[x][y] = dic[countBomb]; countBomb = 0; return; } // 八个方向 for (int i = 0; i < 8; i++) { int post_x = x + step[i][0]; int post_y = y + step[i][1]; board[x][y] = 'B'; sign[x][y] = 1; updateBoardDfs(board, post_x, post_y, sign); } }
publicvoidgetCountBomb(char[][] board, int x, int y){ for (int i = 0; i < 8; i++) { int post_x = x + step[i][0]; int post_y = y + step[i][1]; if (post_x >= height || post_x < 0 || post_y >= width || post_y < 0) continue; if (board[post_x][post_y] == 'M') countBomb++; } }
classSolution{ publicintshipWithinDays(int[] weights, int D){ int left = Arrays.stream(weights).max().getAsInt(); int right = Arrays.stream(weights).sum(); while (left < right){ int middle = (left+right) >> 1; int needDay = 1; int sum = 0; for (int goodWeight : weights){ if (sum + goodWeight > middle){ needDay++; sum = 0; } sum += goodWeight; } if (needDay <= D){ right = middle; } else { left = middle + 1; } } return right; }