首页 > 编程语言 > 详细

LeetCode-1313 Decompress Run-Length Encoded List solutions (with Java and python)

时间:2020-03-02 12:28:59      阅读:47      评论:0      收藏:0      [点我收藏+]

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 的使用

 

LeetCode-1313 Decompress Run-Length Encoded List solutions (with Java and python)

原文:https://www.cnblogs.com/sheepcore/p/12394547.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!