LeetCode-1313 Decompress Run-Length Encoded List solutions (with Java and python)
1. Description:
Notes:
2. Examples:
3.Solutions:
Java Version 1:
1 /** 2 * @author sheepcore 3 * created on 2020-03-02 4 */ 5 public int[] decompressRLElist(int[] nums) { 6 int[] res = new int[100000]; 7 int size = 0; 8 for(int i = 0; i < nums.length; i += 2) { 9 int freq = nums[i]; 10 int val = nums[i + 1]; 11 for(int j = 0; j < freq; j++) { 12 res[size++] = val; 13 } 14 } 15 return Arrays.copyOf(res, size); 16 }
Java Version 2:
1 /** 2 * @author sheepcore 3 * created on 2020-03-02 4 */ 5 public int[] decompressRLElistV2(int[] nums) { 6 List<Integer> res = new ArrayList<>(); 7 for(int i = 0; i < nums.length; i += 2) { 8 int freq = nums[i]; 9 int val = nums[i+1]; 10 while(freq-- != 0) { 11 res.add(val); 12 } 13 } 14 int[] outputs = new int[res.size()]; 15 for(int i = 0; i < res.size(); i++) { 16 outputs[i] = res.get(i); 17 } 18 return outputs; 19 }
One-line Python Version:
1 """ 2 created by lee215 3 """ 4 def decompressRLElist(self, A): 5 return [x for a, b in zip(A[0::2], A[1::2]) for x in [b] * a]
4. Summary:
-
Java 中如何完成数组的复制 Arrays.copyOf(int[] origin, int newLength)
-
python 中 zip 的使用
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步