CarreerCup Sort Height

265 篇文章 1 订阅
86 篇文章 0 订阅
You are given two array, first array contain integer which represent heights of persons and second array contain how many persons in front of him are standing who are greater than him in term of height and forming a queue. Ex
A: 3 2 1
B: 0 1 1
It means in front of person of height 3 there is no person standing, person of height 2 there is one person in front of him who has greater height then he, similar to person of height 1. Your task to arrange them
Ouput should be.
3 1 2

Here - 3 is at front, 1 has 3 in front ,2 has 1 and 3 in front.





*********************************************Solution**************************************************************************************

Arrange From the highest to the next....


Though I like the idea of sorting using the comparator as mentioned above by amitb2108 but below is the approach that came to my mind first.
lets say height[] = {3,1,2,4}
pos[] = {0,2,1,0}; //no of persons greater height than him
1. create an array of person struct of size n and fill the data from the above two arrays
struct person
{
int height;
int num;
};
2. Sort the person array with height as the key in decreasing order. o(nlgn)
index 0,1,2,3
person[] = {4,3,2,1}
{0,0,1,2} //person.num
3. Remember the index of array represents the no of persons greater in front of the current index. e.g. person with height 3 has array index 1, so 1 person is in front of him with greater height. But we need to have 0 no of person greater than 3, so swap it with index 0.
person[] = {3,4,2,1} //after swapping 3
//2 has only one person in front but index of 2 is 2 currently there are 2 persons
//swap it with index 1
person[] = {3,2,4,1}
//1 has only 2 persons in front but index of 1 is 3, so currently there are 3 persons
//swap it with index 2
person[] = {3,2,1,4}
the idea is, previous index, has a person with greater height than current index. The previous index person's position is already set. Now if we move this previous index person towards right it doesn't impact the position of this person. e.g. person with height 4, if we move this person towards the right, still the no of persons with greater height will be 0.
Total complexity = o(nlogn)
*********************************************Solution**************************************************************************************
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值