金塊問題

來源:互聯網
上載者:User

標籤:金塊問題   java   演算法   

金塊問題

題目:老闆有一袋金塊(共 n 塊,n 是 2 的冪( n ≥ 2 )),最優秀的僱員得到其中最重的一塊,最差的僱員得到其中最輕的一塊。假設有一台比較重量的儀器,希望用最少的比較次數找出最重和最輕的金塊。並對自己的程式進行複雜性分析。

import java.util.Scanner;public class Main {private static void minmax(int i, int j, int[] gold, int[] result) {int[] ltemp = new int[2];int[] rtemp = new int[2];if (i == j - 1) {if (gold[i] <= gold[j]) {result[0] = gold[i];result[1] = gold[j];} else {result[0] = gold[j];result[1] = gold[i];}} else {int mid = (i + j) / 2;minmax(i, mid, gold, ltemp);minmax(mid + 1, j, gold, rtemp);if (ltemp[0] <= rtemp[0]) {result[0] = ltemp[0];} else {result[0] = rtemp[0];}if (ltemp[1] >= rtemp[1]) {result[1] = ltemp[1];} else {result[1] = rtemp[1];}}}public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while (scanner.hasNext()) {int n = scanner.nextInt();int[] gold = new int[n];for (int i = 0; i < n; i++) {gold[i] = scanner.nextInt();}int[] result = new int[2];minmax(0, n - 1, gold, result);System.out.println("min: " + result[0]);System.out.println("max: " + result[1]);}scanner.close();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.