【Leetcode】1313. Decompress Run-Length Encoded List

news/2024/7/5 1:11:47

题目地址:

https://leetcode.com/problems/decompress-run-length-encoded-list/

给定一个数组 A A A,要求产生一个新的数组 B B B,产生的方式是,先填 A [ 0 ] A[0] A[0] A [ 1 ] A[1] A[1],再填 A [ 2 ] A[2] A[2] A [ 3 ] A[3] A[3],以此类推。数据保证合法。

代码如下:

public class Solution {
    public int[] decompressRLElist(int[] nums) {
        int cnt = 0;
        for (int i = 0; i < nums.length; i += 2) {
            cnt += nums[i];
        }
        
        int[] res = new int[cnt];
        for (int i = 0, idx = 0; i < nums.length; i += 2) {
            for (int j = 0; j < nums[i]; j++) {
                res[idx++] = nums[i + 1];
            }
        }
        
        return res;
    }
}

时间复杂度 O ( n + ∑ i A [ 2 i ] ) O(n+\sum_{i} A[2i]) O(n+iA[2i]),空间 O ( ∑ i A [ 2 i ] ) O(\sum_{i} A[2i]) O(iA[2i])

C++:

class Solution {
 public:
  vector<int> decompressRLElist(vector<int>& nums) {
    vector<int> res;
    for (int i = 0; i < nums.size(); i += 2)
      for (int j = 0; j < nums[i]; j++)
        res.push_back(nums[i + 1]);

    return res;
  }
};

时空复杂度一样。


http://www.niftyadmin.cn/n/3641962.html

相关文章

将dataTable转成表格

//内容很好理解&#xff0c;只需当成Table来拼字符串即可 private string getExcelContent(DataTable dt) { StringBuilder sb new StringBuilder(); sb.Append("<table>"); sb.Append("<thead><tr>"); for (int m 0; m < dt.Colu…

HTML5设计原理(转)

HTML5设计原理 2010年10月21日 Web开发, 翻译 Jeremy Keith在 Fronteers 2010 上的主题演讲 特别感谢以下朋友指出翻译错误。 rukey67指出了一个翻译错误&#xff08;另一个没有翻错&#xff09;。 梁海指出了一个翻译错误。 小乐指出了一个错别字。 下载PPT&#xff08;PDF&a…

【Leetcode】1221. Split a String in Balanced Strings

题目地址&#xff1a; https://leetcode.com/problems/split-a-string-in-balanced-strings/ 给定一个长nnn的字符串sss&#xff0c;恰好含n/2n/2n/2个字符L和n/2n/2n/2个字符R&#xff0c;题目保证nnn是偶数。问其能分为最多多少个非空的&#xff0c;且两个字符个数相等的子…

【Leetcode】1791. Find Center of Star Graph

题目地址&#xff1a; https://leetcode.com/problems/find-center-of-star-graph/ 给定一个nnn个顶点的无向图&#xff0c;给出所有的n−1n-1n−1条边&#xff0c;题目保证其为星形图&#xff0c;即只有一个点在中心&#xff0c;其余点都与它相连。求中心点编号。 边是以两…

How to: Modify a Project System So That Projects Load in Multiple Versions of Visual Studio

How to: Modify a Project System So That Projects Load in Multiple Versions of Visual Studio http://msdn.microsoft.com/en-us/library/hh266706(vVS.110).aspx posted on 2014-02-21 12:02 K3 阅读(...) 评论(...) 编辑 收藏 转载于:https://www.cnblogs.com/sskset/p/3…

java与Groovy的整合(I)

Groovy是构建在JVM上的一个轻量级却强大的动态语言.因为Groovy就是用Java写的,Groovy可以做到与Java的无缝兼容,可以使用Java强大的类库 而且Groovy最终也会被编译成class文件. Groovy在1.0版的时候还存在性能问题,因为Groovy的很多实现都是用反射来做的,但是现在Groovy 1.1快…

设计模式:中介者模式(Mediator)

定 义&#xff1a;用一个中介对象来封装一系列对象的交互。中介者使各个对象不需要显示地相互作用&#xff0c;从而耦合松散&#xff0c;而且可以独立的改变他们之间的交互。 结构图&#xff1a; Mediator类&#xff0c;抽象中介者类 abstract class Mediator{public abstrac…

java与Groovy的整合(II)

Groovy与流行框架的集成 1.与Spring的集成 现在Spring的核心包就提供了与Groovy的集成了,,很好,很强大,这样就可以显示业务逻辑的动态改变了 由于Groovy的代码中也有描述Java代码的机制&#xff0c;因此两者合用非常容易 Spring Bean: 代码 class"org.springframework.bea…