You are given an array of people,
Reconstruct and return the queue that is represented by the input array
people
, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki]
represents the ith
person of height hi
with exactly ki
other people in front who have a height greater than or equal to hi
.Reconstruct and return the queue that is represented by the input array
people
. The returned queue should be formatted as an array queue
, where queue[j] = [hj, kj]
are the attributes of the jth
person in the queue (queue[0]
is the person at the front of the queue).Example 1:
Input: people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
Output: [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.Comparator;import java.util.List;public class QueueReconstructionByHeight {public static void main(String[] args) {int people[][] = { { 7, 0 }, { 4, 4 }, { 7, 1 },{ 5, 0 }, { 6, 1 }, { 5, 2 } };int rec[][] = reconstructQueue(people);System.out.println(Arrays.deepToString(rec));}// function to reconstruct the queuestatic int[][] reconstructQueue(int[][] people) {// sort array based on conditionArrays.sort(people, new Comparator<int[]>() {@Overridepublic int compare(int[] a, int[] b) {if (a[0] == b[0])if (a[1] < b[1])return -1;elsereturn 1;else if (a[0] > b[0])return -1;elsereturn 1;}});List<int[]> res = new ArrayList<int[]>();if (people.length == 0)return null;// add all elemnt in resultfor (int i = 0; i < people.length; i++) {res.add(people[i][1], people[i]);}// convert list to 2d arrayint a[][] = new int[people.length][2];for (int i = 0; i < res.size(); i++) {a[i] = res.get(i);}return a;}}
C++
#include <bits/stdc++.h>using namespace std;//comparator used to sort the arraystatic bool cmp(vector<int> a ,vector<int> b){if(a[0]==b[0])return a[1]<b[1];elsereturn a[0]>b[0];}//function to reconstruct the queuevector<vector<int>> reconstructQueue(vector<vector<int>>& people){sort(people.begin(),people.end(),cmp);vector<vector<int>> res;if(people.size()==0)return res;for(int i=0;i<people.size();i++)res.insert(res.begin()+people[i][1],people[i]);return res;}int main(){vector<vector<int>> people ={{7,0},{4,4},{7,1},{5,0},{6,1},{5,2}};people=reconstructQueue(people);cout<<"[";for(int i=0;i<people.size();i++){cout<<"["<<people[i][0]<<" "<<people[i][1]<<"]";if(i!=people.size()-1)cout<<",";}cout<<"]";return 0;}
No comments:
Post a Comment