2014年阿里巴巴筆試題目(28題):最小三元數組距離最優算法

題目描述:三個升序整形數組

三個數組分別爲a,b,c。思想是這樣的,每個數組維護一個索引,索引分別爲ap,bp和cp,初始化索引均指向數組開頭的0位置。距離最小值記爲min,主循環如下:(如果其中的某一個索引值超過自身數組大小,則跳出循環),每次讀取三個索引中的MIN最小值和MAX最大值(MAX-MIN計算的數值與min最對比,小則替換min),記下最小值對應的索引數組並增加該索引值,繼續進一步循環。JAVA代碼如下:

import java.util.Arrays;

public class TripArrayAbs {
	public static int getArrayIndex(int x, int y, int z) {
		if (x == y && y == z)
			return 0;
		if (x == getMin(x, y, z))
			return 1;
		if (y == getMin(x, y, z))
			return 2;
		return 3;
	}

	public static int getMax(int x, int y, int z) {
		int max = x > y ? x : y;
		return max > z ? max : z;
	}

	public static int getMin(int x, int y, int z) {
		int min = x > y ? y : x;
		return min > z ? z : min;
	}

	public static int getAbsMax(int x, int y, int z) {
		return getMax(x, y, z) - getMin(x, y, z);
	}

	public static int caculateTripArrays(int[] a, int[] b, int[] c) {
		int aL = a.length, bL = b.length, cL = c.length;
		int ap = 0, bp = 0, cp = 0, minp = 0;
		int min = getMax(a[aL-1], b[bL-1], c[cL-1])-getMin(a[ap], b[bp], c[cp]);
		while (ap < aL && bp < bL && cp < cL) {
			if (getAbsMax(a[ap], b[bp], c[cp]) < min)
				min = getAbsMax(a[ap], b[bp], c[cp]);
			minp = getArrayIndex(a[ap], b[bp], c[cp]);
			if (minp == 1)
				ap++;
			else if (minp == 2)
				bp++;
			else if (minp == 3)
				cp++;
			else
				break;
		}
		return min;
	}

	public static void main(String[] args) {
		int[] a = { 2, 32, 4, 5, 6, 7, 8, 10, 22, 31 };
		int[] b = { 40, 12, 18, 91, 16, 17, 18, 21, 23, 32 };
		int[] c = { 25, 29, 11, 15, 19, 20, 25, 26, 28, 41 };
		Arrays.sort(a);//排序
		Arrays.sort(b);
		Arrays.sort(c);
		System.out.println(caculateTripArrays(a, b, c));
	}
}

 

轉載時請註明來源:http://blog.csdn.net/ccfeng2008


發佈了24 篇原創文章 · 獲贊 17 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章