華為上機練習題--按身高找出最佳二人組

來源:互聯網
上載者:User

標籤: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]);
        
    }
}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.