码迷,mamicode.com
首页 > 其他好文 > 详细

华为上机练习题--按身高找出最佳二人组

时间:2014-06-30 09:37:19      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:java   解决方案   华为   算法   

题目:

要从5个人中选取2个人作为礼仪,其中每个人的身高范围为160-190,要求2个人的身高差值最小(如果差值相同的话,选取其中最高的两人),以升序输出两个人的身高。

Smple input:161 189 167 172 188 Sample outPut: 188 189


分析:我的理解就是先逆序排好数值, 然后逐对比较身高差值, 找出身高差值最小的然后输出


代码如下:

package com.wenj.test;
/**
 * 要从5个人中选取2个人作为礼仪,其中每个人的身高范围为160-190,要求2个人的身高差值最小(如果差值相同的话,选取其中最高的两人),以升序输出两个人的身高。
 *      Smple input:161 189 167 172 188 Sample outPut: 188 189
 * @author wenj91-PC
 *
 */

public class TestBestGround {

    public static void main(String args[]){
        String strIn = "161 189 167 172 188";
        TestBestGround tb = new TestBestGround();
        tb.printTheBestGround(strIn);
    }
    
    public void printTheBestGround(String strIn){
        String strTemp = strIn;
        String[] strArr = strTemp.split(" ");
        
        int[] numArr = new int[strArr.length];
        for(int i=0; i<strArr.length; i++){
            numArr[i] = Integer.parseInt(strArr[i]);
        }
        
        for(int i=0; i<numArr.length; i++){
            for(int j=i+1; j<numArr.length; j++){
                if(numArr[i]<numArr[j]){
                    int temp = numArr[i];
                    numArr[i] = numArr[j];
                    numArr[j] = temp;
                }
            }
        }
        
        int aver = numArr[0]-numArr[1];
        int pos = 0;
        
        for(int i=1; i<numArr.length-1; i++){
            int temp = numArr[i]-numArr[i+1];
            if( temp < aver){
                aver = temp;
                pos = i;
            }
        }
        
        System.out.println(numArr[pos+1] + " " + numArr[pos]);
        
    }
}


华为上机练习题--按身高找出最佳二人组,布布扣,bubuko.com

华为上机练习题--按身高找出最佳二人组

标签:java   解决方案   华为   算法   

原文地址:http://blog.csdn.net/wenj91/article/details/35640699

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!