current position:Home>1313. Unzip the coding list (Java / C / C + + / Python / go / trust)
1313. Unzip the coding list (Java / C / C + + / Python / go / trust)
2022-02-01 15:49:19 【White hat of the second leader】
This is my participation 11 The fourth of the yuegengwen challenge 11 God , Check out the activity details :2021 One last more challenge
Thank you very much for reading this article ~
welcome 【 give the thumbs-up 】【 Collection 】【 Comment on 】~
It's not hard to give up , But persistence must be cool ~
I hope all of us can make a little progress every day ~
This paper is written by The white hat of the second leader :https://le-yi.blog.csdn.net/ Original blog ~
1313. Decompress the encoding list :
Give you a compressed list of integers encoded by run length nums
.
Consider each pair of two adjacent elements [freq, val] = [nums[2*i], nums[2*i+1]]
( among i >= 0
), Each pair indicates that there are... In the sub list after decompression freq
The values are val
The elements of , You need to connect all sub lists from left to right to generate the unzipped list .
Please return to the unzipped list .
Examples 1:
Input :
nums = [1,2,3,4]
Output :
[2,4,4,4]
explain :
The first pair [1,2] Represents the 2 The frequency of occurrence is 1, So generate an array [2].
Second pairs [3,4] Represents the 4 The frequency of occurrence is 3, So generate an array [4,4,4].
Finally, connect them together [2] + [4,4,4] = [2,4,4,4].
Copy code
Examples 2:
Input :
nums = [1,1,2,3]
Output :
[1,3,3]
Copy code
Tips :
- 2 <= nums.length <= 100
- nums.length % 2 == 0
- 1 <= nums[i] <= 100
analysis
-
This algorithm problem really doesn't have any special skills , Just simulate according to the meaning of the topic .
-
For most languages, there is support for dynamic data structures , But there is one thing to note about dynamic data structures , When dynamically adding elements , Dynamic expansion occurs , Content copying may also occur .
-
Some of the solutions of the second leader's problems are traversed first , Calculate the total length , This overhead can offset the overhead of dynamic expansion using dynamic data structures .
Answer key
java
class Solution {
public int[] decompressRLElist(int[] nums) {
int len = 0;
for (int i = 0; i < nums.length; i += 2) {
len += nums[i];
}
int[] ans = new int[len];
for (int i = 0, j = 0; i < nums.length; i += 2) {
for (int k = 0; k < nums[i]; ++k) {
ans[j++] = nums[i + 1];
}
}
return ans;
}
}
Copy code
c
/** * Note: The returned array must be malloced, assume caller calls free(). */
int* decompressRLElist(int* nums, int numsSize, int* returnSize){
*returnSize = 0;
for (int i = 0; i < numsSize; i += 2) {
*returnSize += nums[i];
}
int *ans = malloc(*returnSize * sizeof(int));
for (int i = 0, *p = ans; i < numsSize; i += 2) {
while (nums[i]--) {
(*p++) = nums[i + 1];
}
}
return ans;
}
Copy code
c++
class Solution {
public:
vector<int> decompressRLElist(vector<int>& nums) {
vector<int> ans;
for (int i = 0, l = nums.size(); i < l; i += 2) {
ans.insert(ans.end(), nums[i], nums[i + 1]);
}
return ans;
}
};
Copy code
python
class Solution:
def decompressRLElist(self, nums: List[int]) -> List[int]:
return [nums[i + 1] for i in range(0, len(nums), 2) for _ in range(nums[i])]
Copy code
go
func decompressRLElist(nums []int) []int {
l := 0
for i := 0; i < len(nums); i += 2 {
l += nums[i]
}
ans := make([]int, l)
for i, j := 0, 0; i < len(nums); i += 2 {
for k := 0; k < nums[i]; k, j = k+1, j+1 {
ans[j] = nums[i+1]
}
}
return ans
}
Copy code
rust
impl Solution {
pub fn decompress_rl_elist(nums: Vec<i32>) -> Vec<i32> {
(0..nums.len()).step_by(2).flat_map(|i|{
[nums[i + 1]].repeat(nums[i] as usize).into_iter()
}).collect()
}
}
Copy code
Original title transmission gate :https://leetcode-cn.com/problems/decompress-run-length-encoded-list/
copyright notice
author[White hat of the second leader],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202011549181661.html
The sidebar is recommended
- Python logging log error and exception exception callback method
- Learn Python quickly and take a shortcut~
- Python from 0 to 1 (day 15) - Python conditional judgment 2
- Python crawler actual combat, requests module, python to capture headlines and take beautiful pictures
- The whole activity collected 8 proxy IP sites to pave the way for the python proxy pool, and the 15th of 120 crawlers
- Why can't list be used as dictionary key value in Python
- Python from 0 to 1 (day 16) - Python conditional judgment 3
- What is the python programming language?
- Python crawler reverse webpack, a real estate management platform login password parameter encryption logic
- Python crawler reverse, a college entrance examination volunteer filling platform encrypts the parameter signsafe and decrypts the returned results
guess what you like
-
Python simulated Login, selenium module, python identification graphic verification code to realize automatic login
-
Python -- datetime (timedelta class)
-
Python's five strange skills will bring you a sense of enrichment in mastering efficient programming skills
-
[Python] comparison of dictionary dict, defaultdict and orderdict
-
Test driven development using Django
-
Face recognition practice: face recognition using Python opencv and deep learning
-
leetcode 1610. Maximum Number of Visible Points(python)
-
Python thread 03 thread synchronization
-
Introduction and internal principles of Python's widely used concurrent processing Library Futures
-
Python - progress bar artifact tqdm usage
Random recommended
- Python learning notes - the fifth bullet * class & object oriented
- Python learning notes - the fourth bullet IO operation
- Python crawler actual combat: crawl all the pictures in the answer
- Quick reference manual of common regular expressions, necessary for Python text processing
- [Python] the characteristics of dictionaries and collections and the hash table behind them
- Python crawler - fund information storage
- Python crawler actual combat, pyteseract module, python realizes the visualization of boos direct employment & hook post data
- Pit filling summary: Python memory leak troubleshooting tips
- Python code reading (Chapter 61): delaying function calls
- Through the for loop, compare the differences between Python and Ruby Programming ideas
- leetcode 1606. Find Servers That Handled Most Number of Requests(python)
- leetcode 1611. Minimum One Bit Operations to Make Integers Zero(python)
- 06python learning notes - reading external text data
- [Python] functions, higher-order functions, anonymous functions and function attributes
- Python Networkx practice social network visualization
- Data analysis starts from scratch, and pandas reads and writes CSV data
- Python review (format string)
- [pandas learning notes 01] powerful tool set for analyzing structured data
- leetcode 147. Insertion Sort List(python)
- apache2. 4 + windows deployment Django (multi site)
- Python data analysis - linear regression selection fund
- How to make a python SDK and upload and download private servers
- Python from 0 to 1 (day 20) - basic concepts of Python dictionary
- Django -- closure decorator regular expression
- Implementation of home page and back end of Vue + Django tourism network project
- Easy to use scaffold in Python
- [Python actual combat sharing] I wrote a GIF generation tool, which is really TM simple (Douluo continent, did you see it?)
- [Python] function decorators and common decorators
- Explain the python streamlit framework in detail, which is used to build a beautiful data visualization web app, and practice making a garbage classification app
- Construction of the first Django project
- Python crawler actual combat, pyecharts module, python realizes the visualization of river review data
- Python series -- web crawler
- Plotly + pandas + sklearn: shoot the first shot of kaggle
- How to learn Python systematically?
- Analysis on several implementations of Python crawler data De duplication
- leetcode 1616. Split Two Strings to Make Palindrome (python)
- Python Matplotlib drawing violin diagram
- Python crawls a large number of beautiful pictures with 10 lines of code
- [tool] integrated use of firebase push function in Python project
- How to use Python to statistically analyze access logs?