class Solution: def containsDuplicate(self, nums: List[int]) -> bool: seen = set() i = 0 n = len(nums) while i < n: if nums[i] not in seen: seen.add(nums[i]) else: return True i += 1 return False
附上題目鏈接
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: # 判斷每個元素的位置 return [s.index(i) for i in s] == [t.index(i) for i in t]
class Solution(object): def countPrimes(self, n): """ 埃拉託斯特尼篩法 """ if n < 2: return 0 # 初始化,默認每一值爲1 isPrime = [1] * n isPrime[0] = isPrime[1] = 0 # 0和1不是質數,先排除掉 # 埃式篩,把不大於根號n的所有質數的倍數剔除 #首先從 2 開始,我們知道 2 是一個素數,那麼 2 × 2 = 4, 3 × 2 = 6, 4 × 2 = 8... 都不可能是素數了。 #然後我們發現 3 也是素數,那麼 3 × 2 = 6, 3 × 3 = 9, 3 × 4 = 12... 也都不可能是素數了。 # 從2*2開始到n的倍數包括了2*3,所以3不用從3*2開始,直接從3*3開始 for i in range(2, int(n ** 0.5) + 1): if isPrime[i]: # ((n - 1 - i * i) // i + 1) 記錄下i**i到n中的i倍 isPrime[i * i:n:i] = [0] * ((n - 1 - i * i) // i + 1) return sum(isPrime)
面試題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,