class Solution: def thirdMax(self, nums: List[int]) -> int: # 集合去重 nums = list(set(nums)) if len(nums) <= 2: return max(nums) # 三次選擇排序O(3n) -> O(n) for i in range(3): max_index = i for j in range(i+1, len(nums)): if nums[j] > nums[max_index]: max_index = j nums[i], nums[max_index] = nums[max_index], nums[i] return nums[2]
附上題目鏈接
class Solution: def toLowerCase(self, str: str) -> str: for s in str: if ord(s) >= 65 and ord(s) <= 90: str = str.replace(s,chr(ord(s)+32)) return str # 簡潔寫法 # return ''.join([chr(ord(c)+32) if ord(c)>=65 and ord(c)<=90 else c for c in str])
class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: # r1 - c1 == r2 - c2, 一組矩陣的x-y等於一個定值 groups = {} for r, row in enumerate(matrix): for c, val in enumerate(row): if r-c not in groups: groups[r-c] = val elif groups[r-c] != val: return False return True
面試題62. 圓圈中最後剩下的數字 class Solution { public int lastRemaining(int n, int m) { // 模擬法 List<Integer> l
820. 單詞的壓縮編碼 暴力.. class Solution { public int minimumLengthEncoding(String[] words) { String[] temp = ne
1162. 地圖分析 class Solution { public int maxDistance(int[][] grid) { Queue<Node> queue = new LinkedList<>();
914. 卡牌分組 // 暴力.. class Solution { public boolean hasGroupsSizeX(int[] deck) { int[] temp = new int[10000]
1. 兩數之和 暴力: class Solution { public int[] twoSum(int[] nums, int target) { int[] res = new int[2];
8. 字符串轉換整數 (atoi) class Solution { public int myAtoi(String str) { if (str == null || str.length() == 0 ||
01.07. 旋轉矩陣 簡單粗暴: class Solution { public void rotate(int[][] matrix) { int size = matrix.length;
11. 盛最多水的容器 暴力... class Solution { public int maxArea(int[] height) { int max = 0; for (int i
238. 除自身以外數組的乘積 不能用除法,不能額外空間,所以先用一個數組存第 i 位左邊的所有數乘積,再倒過來遍歷賦值:res = 左邊乘積 * 右邊乘積 class Solution { public int[] pro
7. 整數反轉 class Solution { public int reverse(int x) { long result = 0; while (x != 0) { // 如果是-1
20. 有效的括號 class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>();
208. 實現 Trie (前綴樹) class Trie { //定義節點 class TrieNode { boolean isEnd; TrieNode[] next = new
912. 排序數組 class Solution { public int[] sortArray(int[] nums) { quickSort(nums, 0, nums.length - 1);
999. 可以被一步捕獲的棋子數 class Solution { public int numRookCaptures(char[][] board) { if (board == null) {
給定一個數組,將數組中的元素向右移動 k 個位置,其中 k 是非負數。 示例 1: 輸入: [1,2,3,4,5,6,7] 和 k = 3 輸出: [5,6,7,1,2,3,4] 解釋: 向右旋轉 1 步: [7,1,2,3,4,