首页 文章 精选 留言 我的

精选列表

搜索[leetcode],共439篇文章
优秀的个人博客,低调大师

LeetCode 905. 按奇偶排序数组

题目 给定一个非负整数数组 A,返回一个数组,在该数组中,A 的所有偶数元素之后跟着所有奇数元素。 你可以返回满足此条件的任何数组作为答案。 示例: 输入:[3,1,2,4] 输出:[2,4,3,1] 输出 [4,2,3,1],[2,4,1,3] 和 [4,2,1,3] 也会被接受。 提示: 1 <= A.length <= 50000 <= A[i] <= 5000 解题思路 class Solution: def sortArrayByParity(self, A: [int]) -> [int]: # #双指针 # left = 0 # right = len(A)-1 # while left != right: # if A[left] %2 == 0: # left += 1 # continue # if A[right] %2 == 1: # right -= 1 # continue # A[left], A[right] = A[right], A[left] # left += 1 # if left == right:break # right -= 1 # return A #数组 ret = [] for i in A: if i %2 == 0: ret.insert(0,i) else: ret.append(i) return ret

优秀的个人博客,低调大师

LeetCode 205:同构字符串 Isomorphic Strings

题目: 给定两个字符串 s 和 *t*,判断它们是否是同构的。 如果 s 中的字符可以被替换得到 *t* ,那么这两个字符串是同构的。 所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。 Given two strings s* and t*, determine if they are isomorphic. Two strings are isomorphic if the characters in s* can be replaced to get t*. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. 示例 1: 输入: s = "egg", t = "add" 输出: true 示例 2: 输入: s = "foo", t = "bar" 输出: false 示例 3: 输入: s = "paper", t = "title" 输出: true 说明:你可以假设 s 和 *t* 具有相同的长度。 Note:You may assume both s* and t* have the same length. 解题思路: ​ 在示例 3 中输入: s = "paper", t = "title",其中字母映射结果:p <==> t , a <==>i , e <==> l , r <==>e 映射的字母可以一一替换得到对应的单词,这便是同构字符串。 非同构字符串无非两种情况(假设长度相等): s = 'aa' , t = 'ab',在建立过字母映射 a <==> a 后,s第二个字母 a 其映射 value = a 不等于 t 中第二个字母 b s = 'ab' , t = 'aa',在建立过字母映射 a <==> b 后,t第二个字母 a 其映射 key = a 不等于s中第二个字母 b 所以这个可以用两个哈希映射验证上述两种情况,也可以用一个映射加判断是否存在于其 values 中。 ​ 既然是建立映射字符,那么最先想到的就是哈希映射(map、dict)了。 ​ 该题为英文单词字符串同构检测,整个 ASCll 码长度才256,所以这道题也可以用 char[256] 以索引值对应一个字符,其存储值对应一个字符建立映射关系。 还有一个更巧妙的解法,每个字符都与该字符串中第一次出现的索引对比是否相等,判断是否同构。如: 输入:s = 'aa' , t = 'ab' 第一次遍历: s中第一个字符 a 第一次出现的索引为0,t中第一个字符 a 第一次出现的索引为0,索引相等,继续遍历 第二次遍历: s中第二个字符 a 第一次出现的索引为0,t中第二个字符 b 第一次出现的索引为1,索引不相等, 返回false 代码: 双哈希映射: Java: class Solution { public boolean isIsomorphic(String s, String t) { Map<Character, Character> s_map = new HashMap<>(); Map<Character, Character> t_map = new HashMap<>(); char[] s_chars = s.toCharArray(), t_chars = t.toCharArray(); // 转成 cahr 型数组 for (int i = 0; i < s_chars.length; i++) { // 两种不成立的情况 if (s_map.containsKey(s_chars[i]) && s_map.get(s_chars[i]) != t_chars[i]) return false; if (t_map.containsKey(t_chars[i]) && t_map.get(t_chars[i]) != s_chars[i]) return false; s_map.put(s_chars[i], t_chars[i]); t_map.put(t_chars[i], s_chars[i]); } return true; } } Python: class Solution: def isIsomorphic(self, s: str, t: str) -> bool: s_map, t_map = {}, {} # 双字典 for c1, c2 in zip(s, t): # 两种不成立的情况 if c1 in s_map and s_map[c1] != c2: return False if c2 in t_map and t_map[c2] != c1: return False s_map[c1] = c2 t_map[c2] = c1 return True 单哈希映射: Java: class Solution { public boolean isIsomorphic(String s, String t) { Map<Character, Character> map = new HashMap<>();// 一个哈希映射 char[] s_chars = s.toCharArray(), t_chars = t.toCharArray(); for (int i = 0; i < s_chars.length; i++) { if (map.containsKey(s_chars[i]) && map.get(s_chars[i]) != t_chars[i]) return false; // 判断t中字符是否存在于映射中的 values 内 if (!map.containsKey(s_chars[i]) && map.containsValue(t_chars[i])) return false; map.put(s_chars[i], t_chars[i]); } return true; } } Python: class Solution: def isIsomorphic(self, s: str, t: str) -> bool: hash_map = {} for c1, c2 in zip(s, t): if c1 in hash_map and hash_map[c1] != c2: return False # 判断t中字符是否存在于映射中的 values 内 if c1 not in hash_map and c2 in hash_map.values(): return False hash_map[c1] = c2 return True 字符首次出现的索引对比法: Java: class Solution { public boolean isIsomorphic(String s, String t) { char[] s_chars = s.toCharArray(); char[] t_chars = t.toCharArray(); for (int i = 0; i < s.length(); i++) { // 判断该字符首次出现索引值是否相等 if (s.indexOf(s_chars[i]) != t.indexOf(t_chars[i])) { return false; } } return true; } } Python: class Solution: def isIsomorphic(self, s: str, t: str) -> bool: for c1, c2 in zip(s, t): # 判断该字符首次出现索引值是否相等 if s.find(c1) != t.find(c2): return False return True 256位字符映射 Java class Solution { public boolean isIsomorphic(String s, String t) { char[] s_chars = s.toCharArray(), t_chars = t.toCharArray(); char[] s_map = new char[256], t_map = new char[256]; //索引与存储值建立映射 for (int i = 0; i < s_chars.length; i++) { char sc = s_chars[i], tc = t_chars[i]; if (s_map[sc] == 0 && t_map[tc] == 0) { s_map[sc] = tc; t_map[tc] = sc; } else if (s_map[sc] != tc || t_map[tc] != sc) {//索引与元素值的映射是否满足条件 return false; } } return true; } } python中没有字符这一基础数据 欢迎关注微。信。公。众。号:爱写Bug

优秀的个人博客,低调大师

LeetCode 217:存在重复元素 Contains Duplicate

题目: 给定一个整数数组,判断是否存在重复元素。 Given an array of integers, find if the array contains any duplicates. 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。 Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct. 示例 1: 输入: [1,2,3,1] 输出: true 示例 2: 输入: [1,2,3,4] 输出: false 示例 3: 输入: [1,1,1,3,3,4,3,2,4,2] 输出: true 解题思路: ​ 排序数组,连续两个数相等则证明存在重复元素。 ​ 直接用哈希集合:新建一个哈希集合,逐个向集合内添加元素,如果遇到元素未添加成功,则证明存在重复元素,返回 True ,反之返回 False。 代码: 这里用的哈希集合解题 Java: class Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> set = new LinkedHashSet<>(); for (int num : nums) { if (!set.add(num)) return true; //加入集合未成功,证明集合内已有一个相同元素,返回False } return false; } } Python: ​ Python中 set() 函数可以直接将数组转化为哈希集合。直接比较转化后的哈希集合长度与原数组长度是否相等,相等证明原数组无重复元素,不相等则证明原数组含有重复元素。 class Solution: def containsDuplicate(self, nums: List[int]) -> bool: return len(nums) != len(set(nums)) #比较长度 欢迎关注微.信公.众号:爱写Bug

优秀的个人博客,低调大师

LeetCode 752:打开转盘锁 Open the Lock

题目: 你有一个带有四个圆形拨轮的转盘锁。每个拨轮都有10个数字: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' 。每个拨轮可以自由旋转:例如把 '9' 变为 '0','0'变为 '9' 。每次旋转都只能旋转一个拨轮的一位数字。 锁的初始数字为 '0000' ,一个代表四个拨轮的数字的字符串。 列表 deadends 包含了一组死亡数字,一旦拨轮的数字和列表里的任何一个元素相同,这个锁将会被永久锁定,无法再被旋转。 字符串 target 代表可以解锁的数字,你需要给出最小的旋转次数,如果无论如何不能解锁,返回 -1。 You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. The lock initially starts at '0000', a string representing the state of the 4 wheels. You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. 示例 1: 输入:deadends = ["0201","0101","0102","1212","2002"], target = "0202" 输出:6 解释: 可能的移动序列为 "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202"。 注意 "0000" -> "0001" -> "0002" -> "0102" -> "0202" 这样的序列是不能解锁的, 因为当拨动到 "0102" 时这个锁就会被锁定。 示例 2: 输入: deadends = ["8888"], target = "0009" 输出:1 解释: 把最后一位反向旋转一次即可 "0000" -> "0009"。 示例 3: 输入: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" 输出:-1 解释: 无法旋转到目标数字且不被锁定。 示例 4: 输入: deadends = ["0000"], target = "8888" 输出:-1 提示: 死亡列表 deadends 的长度范围为 [1, 500]。 目标数字 target 不会在 deadends 之中。 每个 deadends 和 target 中的字符串的数字会在 10,000 个可能的情况 '0000' 到 '9999' 中产生。 Note: The length of deadends will be in the range [1, 500]. target will not be in the list deadends. Every string in deadends and the string target will be a string of 4 digits from the 10,000 possibilities '0000' to '9999'. 解题思路: 题目要求给出最小的旋转次数,应该就是用 BFS(广度优先搜索)解题了。初始字符串为 "0000" 那么第二步就是 "1000" "9000" "0100" "0900" "0010" "0090" "0001" "0009" 共八个字符串,也就是说每一步的字符串拨动密码扩展到下一步时可以得到八个新字符串。把它想象成图的形式:很明显相当于每个节点后有八个节点,用 BFS 每次走一个节点,直到达到目标节点,即是最短路径。 另外需要注意:每次到要判断节点是否为给出的死亡数字,并且把已遍历的节点也加入死亡数字以防止重复。这样只能将原数组形式的死亡数字转为哈希表以减少查找操作的复杂度。用队列暂存下一步需要遍历的节点。Java、python无法直接修改字符串里的字符.Java可先转换成 char 型数组,python可借助切片组装新字符串。 Java: class Solution { public int openLock(String[] deadends, String target) { HashSet<String> dead_set = new HashSet<>(Arrays.asList(deadends));//死亡数字转为哈希表 if (dead_set.contains("0000")) return -1;//死亡数字如果含有初始节点,返回-1 Queue<String> queue = new LinkedList<>();//队列 queue.add("0000");//加入初始节点 int count = 0;//记录步数 while (!queue.isEmpty()) {//节点未访问完,队列内的节点不为空 int size = queue.size();//每一步节点数 while (size-- > 0) { String tmp = queue.remove();//弹出头节点 if (target.equals(tmp)) return count;//如果与目标数相同,直接返回步数 char[] c = tmp.toCharArray();//转为数组 for (int j = 0; j < 4; j++) {//每次修改四位数字的一位 int i = c[j] - '0';//转为int型 c[j] = (char) ('0' + (i + 9) % 10);//数字-1。余数运算可防止节点为0、9时出现-1、10的情况 String s = new String(c);//得到新字符串 if (!dead_set.contains(s)) {//字符串不在死亡数字中时 queue.add(s);//添加到队列作为下一步需要遍历的节点 dead_set.add(s);//下一步必访问该节点,所以可先加入到死亡数字 } c[j] = (char) ('0' + (i + 11) % 10);//数字+1 s = new String(c); if (!dead_set.contains(s)) { queue.add(s); dead_set.add(s); } c[j] = (char) ('0' + i); } } count++; } return -1; } } Python: class Solution: def openLock(self, deadends: List[str], target: str) -> int: #转成哈希表 dead_set = set(deadends) if '0000' in dead_set: return -1 que = collections.deque(['0000']) count = 0 while que: for x in range(len(que)): #从左取出头节点 tmp = que.popleft() if tmp == target: return count for i in range(4): #分别存修改字符的左半部分字符串,待修改字符(转成int),右半部分字符 left, mid, right = tmp[:i], int(tmp[i]), tmp[i + 1:] #j数字加一、减一拨动操作 for x in [-1, 1]: s = left + str((mid + x) % 10) + right#切片拼接字符 if not s in dead_set: dead_set.add(s) que.append(s) count += 1 return -1 关注微.信.公.众号:爱写Bug,一起学习吖

优秀的个人博客,低调大师

LeetCode 394:字符串解码 Decode String

题目: 给定一个经过编码的字符串,返回它解码后的字符串。Given an encoded string, return its decoded string. 编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. 你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc. 此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4]. 示例: s = "3[a]2[bc]", 返回 "aaabcbc". s = "3[a2[c]]", 返回 "accaccacc". s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef". 解题思路: ​ 这道题类似我们之前做过的一道题:有效的括号: https://mp.weixin.qq.com/s/Sm1S26EgR-dC75hrhVnZGQ 只不过''有效的括号'' [] 内多了一些字符串需要操作。我们同样可以用数据结构栈来解题,,能用栈解决的题目大部分都可以用递归解决,两者逻辑基本相同: 输入:'3[a2[c]]' 初始化栈: 栈nums 存要重复的次数k,栈str 存字符串 遍历字符串: 指针指向字符'3',为数字 num暂存数字3 继续遍历,遇到字符'[' 循环次数num入栈nums,空字符串res入栈str nums: 3 res: '' num置为0,str置空 继续遍历,遇到字符'a',为字母 空字符串res拼接字母'a',res='a' 继续遍历,遇到字符'2',为数字 num暂存数字2 继续遍历遇到字符'[' num入栈nums,res入栈str nums: 3 -> 2 str: '' -> 'a' num置为0,str置空 继续遍历,遇到字符'c',为字母 空字符串res拼接字母'c',res='c' 继续遍历遇到字符']' nums弹出栈顶元素:当前字符串重复次数2 res = res*2 = 'cc' str弹出栈顶元素'a'与res拼接并入栈: res = 'a'+'cc'='acc' str: '' -> 'acc' 继续遍历遇到字符']' nums弹出栈顶元素:当前字符串重复次数3 res = res*3 = 'accaccacc' str弹出栈顶元素空字符串''与res拼接并入栈: res=''+'accaccacc'='accaccacc' str: 'accaccacc' 结束返回res 注意: 由于重复次数可能大于10,所以暂存数字时要适当处理,如 num*10+当前数字 在c++里可以直接修改拼接字符,但Java不支持运算符重载,可以借助 StringBuilder 或 StringBuffer 类。 用栈暂存的逻辑与递归基本一致,可以理解为用递归实现栈。 python没有栈这种数据结构,可以用 list() 数组或双端队列 deque() python可以只用一个栈以元组的形式重复次数和字符串,如(num,res) 利用栈: Java: class Solution { public String decodeString(String s) { //初始化数据结构 Stack<StringBuilder> str = new Stack<>(); Stack<Integer> nums = new Stack<>(); StringBuilder res = new StringBuilder(); int num = 0; for (char c : s.toCharArray()) {//递归字符串 if (c == '[') { str.push(res);//入栈 nums.push(num); num = 0;//刷新num、res res = new StringBuilder(); } else if (c == ']') { StringBuilder tmp = new StringBuilder(); for (int i = nums.pop(); i > 0; i--) tmp.append(res);//res*3 res = str.pop().append(tmp); } else if (c >= '0' && c <= '9') num = num * 10 + (c - '0');//计算重复次数 else res.append(c); } return res.toString(); } } Python: 可直接操作字符串真的很方便。py里有现成的判断字符串的方法: isdigit() 是否为只包含数字的字符串 isalpha() 是否为只包含字母的字符串 class Solution: def decodeString(self, s: str) -> str: #初始化数据结构 stack, res, num = [], '', 0 for c in s: if c.isdigit(): num = num * 10 + int(c) elif c.isalpha(): res += c elif c == '[': #元组形式入栈 stack.append((res, num)) #刷新字符串和重复次数 res, num = '', 0 else: #如果c==']',弹出字符串和重复次数 last_str, this_num = stack.pop() res = last_str + this_num * res return res 利用递归: Java: 将 s.length() 的值以参数传递,减少重复调用 length() 造成的时间损耗 class Solution { private int i = -1;//全局变量i,记录字符数组指针位置 public String decodeString(String s) { return dfs(s.toCharArray(), s.length()).toString(); } //递归函数 private StringBuilder dfs(char[] chars, int len) { int num = 0; StringBuilder str = new StringBuilder(); while (++i < len) { if (chars[i] >= '0' && chars[i] <= '9') num = num * 10 + (chars[i] - '0'); else if (chars[i] == '[') { StringBuilder tmp = dfs(chars, len);//递归调用 while (--num >= 0) str.append(tmp);//重复字符串res=res*num num = 0; } else if (chars[i] == ']') return str; else str.append(chars[i]); } return str; } } Python: class Solution: i = -1 #递归函数,可以直接操作字符串就无需再建一个dfs辅助函数 def decodeString(self, s: str) -> str: res, num = '', 0 while self.i < len(s) - 1: self.i += 1 if s[self.i].isdigit(): num = num * 10 + int(s[self.i]) elif s[self.i].isalpha(): res += s[self.i] elif s[self.i] == '[': #递归调用 res += self.decodeString(s) * num num = 0 elif s[self.i] == ']': return res return res 欢迎关注微.信公.众号:爱写Bug

优秀的个人博客,低调大师

LeetCode第14题:最长公共前缀

题目: 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。 示例 1:输入: ["flower","flow","flight"]输出: "fl" 示例 2:输入: ["dog","racecar","car"]输出: ""解释: 输入不存在公共前缀。说明: 所有输入只包含小写字母 a-z 。 代码: class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ res = '' # 排除特殊情况 if len(strs) == 0: return res if len(strs) == 1: return strs[0] min_length = len(strs[0]) # 找到最短的字符串,确定循环次数 for i in range(1, len(strs)): if len(strs[i]) < min_length: min_length = len(strs[i]) for i in range(min_length): tmp_char = strs[0][i] # 用每个字符串的第i个元素和第0个字符串的第i个元素对比 for j in range(1, len(strs)): # 不等则清除tmp_char并结束 if strs[j][i] != tmp_char: tmp_char = "" if tmp_char == "": break res += tmp_char return res 自己写的太烂了,cp个范例。。。 本文链接:时光不写博客-最长公共前缀

优秀的个人博客,低调大师

LeetCode 561:数组拆分 I Array Partition I

文章全部来自公众号:爱写bug 算法是一个程序的灵魂。Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. 给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大。 Example 1: Input: [1,4,3,2] Output: 4 Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4). Note: n is a positive integer, which is in the range of [1, 10000]. All the integers in the array will be in the range of [-10000, 10000]. 提示: n 是正整数,范围在 [1, 10000]. 数组中的元素范围在 [-10000, 10000]. 解题思路: ​ 其实就是把 数组排序,然后按顺序 每两个数既是一对,每对的第一个数累加之和即为所求。就是考一下各类排序算法的性能。 先使用内置 sort() 函数理解一下思路: Java: import java.util.Arrays; class Solution { public int arrayPairSum(int[] nums) { Arrays.sort(nums); int sum=0; for (int i=0;i<nums.length;i+=2){ sum+=nums[i]; } return sum; } } 扩展: 维基百科上对排序算法介绍的非常详细,并且进行了归类比较,地址: 这里简单推荐两个: 快速排序(quick sort)—期望时间,最坏情况;对于大的、随机数列表一般相信是最快的已知排序(C语言标准库的qsort()排序用的就是快速排序算法,利用递归和分而治之思想) 桶排序(bucket sort)—;需要额外空间(典型的牺牲空间换时间) 冒泡排序、选择排序都是比较简单容易理解,复杂度是 n^2 ,所以不再赘述。

优秀的个人博客,低调大师

「翻转图像」python之leetcode刷题|003

镇楼 题目 给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。 水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。 反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。 示例 1: 输入: [[1,1,0],[1,0,1],[0,0,0]] 输出: [[1,0,0],[0,1,0],[1,1,1]] 解释: 首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]]; 然后反转图片: [[1,0,0],[0,1,0],[1,1,1]] 示例 2: 输入: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]] 输出: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 解释: 首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]; 然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]] 说明: 1 <= A.length = A[0].length <= 20 0 <= A[i][j] <= 1 解答 这道题是数组操作,遇上python用列表切片操作完美解决,同时复习上一题的位运算。 class Solution: def flipAndInvertImage(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ for i in range(len(A)): for j in range(len(A[0])): A[i][j] = A[i][j]^1 A[i] = A[i][::-1] return A 用两层for循环来操作二维数组里的元素,进行异或位运算。再用python中列表的切片操作翻转列表元素。 看一下执行结果 执行结果 看一下网友代码: class Solution: def flipAndInvertImage(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ result = [] for line in A: line = line[::-1] result.append(list(map(lambda a : int(a!=1),line))) return result 刚开始也是想用map()函数,把元素遍历出来,得到结果的数字,没有生成列表。网友代码是先把元素逆序,然后再进行翻转。 这里用到了lambda匿名函数,这个函数的的作用是翻转数字。 外层嵌套的map()函数接受两个参数,一个是匿名函数lambda,一个是列表。 因为map()函数是惰性,所以用list函数求出列表。 你有更好的解答方法吗,公众号sixkery,欢迎一起交流。

优秀的个人博客,低调大师

LeetCode 1313. 解压缩编码列表

题目 给你一个以行程长度编码压缩的整数列表nums。 考虑每对相邻的两个元素 [freq, val] = [nums[2i], nums[2i+1]](其中i >= 0),每一对都表示解压后子列表中有 freq个值为val的元素,你需要从左到右连接所有子列表以生成解压后的列表。 请你返回解压后的列表。 示例: 输入:nums = [1,2,3,4] 输出:[2,4,4,4] 解释:第一对 [1,2] 代表着 2 的出现频次为 1,所以生成数组 [2]。 第二对 [3,4] 代表着 4 的出现频次为 3,所以生成数组 [4,4,4]。 最后将它们串联到一起 [2] + [4,4,4] = [2,4,4,4]。 示例 2: 输入:nums = [1,1,2,3] 输出:[1,3,3] 提示: 2 <= nums.length <= 100nums.length % 2 == 01 <= nums[i] <= 100 解题思路 class Solution: def decompressRLElist(self, nums: [int]) -> [int]: ret = [] countList = nums[::2] valueList = nums[1::2] for i in range(len(countList)): count = countList[i] ret += [valueList[i]]*count return ret

优秀的个人博客,低调大师

Leetcode 118:Pascal's Triangle 杨辉三角

118:Pascal's Triangle 杨辉三角 Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。 In Pascal's triangle, each number is the sum of the two numbers directly above it. 在杨辉三角中,每个数是它左上方和右上方的数的和。 Example: Input: 5 Output: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 解题思路: ​ 第一行第二行都是1,每行第一个和最后一个都为1,假设其他位置的数x索引坐标是(m,n),则x就是数是它 索引正上方的数和索引正上方的左边的数 之和。即(m-1,n),(m-1,n-1)两数和。 java: class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> triangle = new ArrayList<List<Integer>>(); if(numRows == 0) return triangle; List<Integer> one = new ArrayList<Integer>(); one.add(1); triangle.add(one); if(numRows == 1) return triangle; for (int i=1;i<numRows;i++){ List<Integer> row = new ArrayList<Integer>(); row.add(1); for (int j=1;j<i;j++){ List<Integer> prev = triangle.get(i-1); row.add(prev.get(j-1)+prev.get(j)); } row.add(1); triangle.add(row); } return triangle; } } python: class Solution: def generate(self, numRows: int) -> List[List[int]]: if numRows==0:return [] triangle=[[1]] if numRows==1: return triangle for i in range(1,numRows): tmp=[1] for j in range(1,i): tmp.append(triangle[i-1][j-1]+triangle[i-1][j]) tmp.append(1) triangle.append(tmp) return triangle 总结: 很简单的一道题,可以复习一下java嵌套数组数据结构。另外 可以在内层循环加判断 if(i!=0) row.add(1);triangle.add(row); 在i不等于0时才加上1,这样可省略 List<Integer> one = new ArrayList<Integer>(); one.add(1); triangle.add(one); if(numRows == 1) return triangle; 代码段,但是这个 if(i!=0)会在每次进入第一次循环后判断一次。本着减少资源消耗的原则,应当提到外面。

优秀的个人博客,低调大师

java -----------------LeetCode——电话号码的字母组合

回溯算法是不是很是陌生啊,我敢开始也是一脸你蒙蔽,后来我终于忍不住了,就去查查什么是回溯,原来是这个情况,回溯和递归有点类似,但是又不是递归,比如我现在计算数据从0开始到2,当到达状态值2我就回溯,我从1开始回溯,我在回到0,就是for循环我不按套路从小到打,去输出了,我采用回溯, public class Main { public static void main(String[] args) { List<String> stringList = begin("23"); System.out.println(stringList.toString()); } // 定义每个数字对应的字符 static String[] a = new String[] {"","","abc","def", "ghi","jkl","mno","pqrs","tuv","wxyz"}; // 这个是输出的字符串 static StringBuffer sb = new StringBuffer(); private static List<String> begin(String str) { if (str.length() == 0) { return null; } List<String> result = new ArrayList<>(15); zihe(str,0,result); return result; } private static void zihe(String str, int n, List<String> result) { if (n == str.length()) { result.add(sb.toString()); return; } for (int i = 0; i < a[str.charAt(n)-'0'].length(); i++) { sb.append(a[str.charAt(n)-'0'].charAt(i)); zihe(str, n + 1, result); sb.deleteCharAt(sb.length() - 1); } } }

优秀的个人博客,低调大师

Leetcode打卡 | No.012 整数转罗马数字

No.12 整数转罗马数字 原题: 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。 字符 数值I 1V 5X 10L 50C 100D 500M 1000例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。 通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况: I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。 X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。 给定一个整数,将其转为罗马数字。输入确保在 1 到 3999 的范围内。 示例: 示例 1: 输入: 3 输出: "III" 示例 2: 输入: 4 输出: "IV" 示例 3: 输入: 9 输出: "IX" 示例 4: 输入: 1994 输出: "MCMXCIV" 解释: M = 1000, CM = 900, XC = 90, IV = 4. 分析:最为简单粗暴的方法,可以使用面向过程的思路,比如给定一个数,逐次从高到低进行转换。一大堆的if~这个思路很容易看懂,这里小詹不做过多解释,看代码! class Solution(object): def intToRoman(self, num): """ :type num: int :rtype: str """ result = '' #简单粗暴!从大到小依次处理,几个关键位置分别是: #1000;900;500;400;100;90;50;40;10;9;5;4;1 while num > 0: if num >= 1000: result += 'M' num -= 1000 elif num >= 900: result += 'CM' num -= 900 elif num >= 500: result += 'D' num -= 500 elif num >= 400: result += 'CD' num -= 400 elif num >= 100: result += 'C' num -= 100 elif num >= 90: result += 'XC' num -= 90 elif num >= 50: result += 'L' num -= 50 elif num >= 40: result += 'XL' num -= 40 elif num >= 10: result += 'X' num -= 10 elif num >= 9: result += 'IX' num -= 9 elif num >= 5: result += 'V' num -= 5 elif num >= 4: result += 'IV' num -= 4 elif num >= 1: result += 'I' num -= 1 return result 上边代码并不难懂,效果一般!这里已经注意到几个特殊的值,可以根据这些值做文章。下边提供一种网上的代码思路:通过构建字典和列表,从高位到低位依次进行转换输出。因为小詹把注释写的很详细,这里就不做赘述了! 原文发布时间为:2018-06-29本文作者:小詹同学本文来自云栖社区合作伙伴“ 小詹学Python”,了解相关信息可以关注“ 小詹学Python”

资源下载

更多资源
腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册