Given a sequence of n integers, where each element is distinct and satisfies. For each x where 1<=x<=n and find any integer y such that and print the value of y on a new line.
Example:
Input: n=5, arr[]={4,3,5,1,2}
Output: 1 3 5 4 2
Approach
Java
import java.util.Arrays;public class SequenceEquation {public static void main(String[] args) {int[] arr = { 4, 3, 5, 1, 2 };int res[] = permutationEquation(arr);System.out.println(Arrays.toString(res));}static int[] permutationEquation(int[] arr) {int n = arr.length;int x = 1, i = 0;int res[] = new int[n];int l = 0;while (x <= n) {if (arr[arr[arr[i] - 1] - 1] == x) {res[l++] = arr[i];i = 0;x = x + 1;} else {i++;}}return res;}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> permutationEquation(vector<int> arr){int n = arr.size();int x = 1, i = 0;vector<int> res;int l = 0;while (x <= n){if (arr[arr[arr[i] - 1] - 1] == x){res.push_back(arr[i]);i = 0;x = x + 1;}else{i++;}}return res;}int main(){vector<int> arr = {4, 3, 5, 1, 2};vector<int> res = permutationEquation(arr);for (int i = 0; i < res.size(); i++){cout << res[i] << " ";}return 0;}
No comments:
Post a Comment