An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, A, of size N, each memory location has some unique index, i (where 0<=i<N), that can be referenced as A[i] or Ai.
Reverse an array of integers.
Example:
Input: n=4,arr[]={1,4,3,2}
Output: 2 3 4 1
Approach
Java
import java.util.Arrays;public class ArraysDS {public static void main(String[] args) {int[] arr = { 1, 4, 3, 2 };int[] rev = reverseArray(arr);System.out.println(Arrays.toString(rev));}private static int[] reverseArray(int[] arr) {int a[] = new int[arr.length];int j = 0;for (int i = a.length - 1; i >= 0; i--) {a[j++] = arr[i];}return a;}}
C++
#include <bits/stdc++.h>using namespace std;vector<int> reverseArray(vector<int> a){vector<int> res;for (int i = a.size() - 1; i >= 0; i--){res.push_back(a[i]);}return res;}int main(){int n = 4;vector<int> arr = {1, 4, 3, 2};vector<int> rev = reverseArray(arr);for (int i = 0; i < rev.size(); i++){cout << rev[i] << " ";}return 0;}
No comments:
Post a Comment