Decompress Run-Length Encoded List

Given an array of length n where n is even and each pair (a[i],a[i+1]) where a[i] is frequency and a[i+1] is the value.

Example 1:

Input: arr[] = {1,2,3,4}
Output: 2 4 4 4 
Explanation: The first pair [1,2] means we have freq = 1 and val = 2.

Approach:

Java


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class DecompressRLElist {
    public static void main(String[] args) {
        int nums[] = { 1234 };
        System.out.println(Arrays.toString(decompressRLElist(nums)));
    }

    public static int[] decompressRLElist(int[] nums) {
        List<Integerlist = new ArrayList<>();
        for (int i = 1; i < nums.length; i = i + 2) {
            int freq = nums[i - 1];
            int val = nums[i];
            for (int k = 0; k < freq; k++) {
                list.add(val);
            }
        }
        int arr[] = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            arr[i] = list.get(i);
        }
        return arr;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

//function to decomrees
//the run length encodin
// pair(a,b) means b occurs a times
vector<intdecompressRLElist(int arr[],int n
{
    vector<intres;
     for(int i=0;i<n;i+=2)
         {
             while(arr[i]--)
             {
                 res.push_back(arr[i+1]);
             }
        }
        return res;
}
int main()
{

    //input array must be of even length
    int arr[]={1,2,3,4};
    int  n=sizeof(arr)/sizeof(arr[0]);
    vector<intnewArr=decompressRLElist(arr,n);
    for(int i=0;i<newArr.size();i++)
       cout<<newArr[i]<<" ";
    return 0;
}
  




No comments:

Post a Comment