部落客頁:http://blog.csdn.net/minna_d
題目:
給一個n個元素的線性表A,對於每個數Ai,找到它之前的數中,和它最接近的數。即對於每個i,計算
Ci = min{|Ai-Aj| | 1<=j<i} 規定C1 = 0。
其實就是給定一個數組, 在a[0....i-1]中求離a[i]最近的值, 其實這裡有個bug,那就是,如果對與6而言5,7都離它一樣, 那麼該輸出誰呢
N久不寫C, 感覺怪怪的, 寫了一個java版。
思路:
用一個臨時數組儲存,離a[i]最近值
用另外一個數組儲存前a[0, i-1]的排序值
這樣一個好處就就是能在result[i-1]的基礎之上計算result[i]的結果,
查詢時間複雜度為lgn,插入時間複雜度為1(因為Arrays.copy中調用System.arraycopy的緣故)
public static void main(String[] args) { List<Integer> list = Lists.newArrayList(1, 8, 6, 6, 7, 5, 4, 1, 0, 8); Integer[] result = new Integer[list.size()]; List<Integer> tmp = Lists.newArrayList(list.get(0)); result[0] = 0; for (int i = 1; i < list.size(); i++) { Integer willBeSort = list.get(i); Integer shouldInsert = Collections.binarySearch(tmp, willBeSort); // 該值已經存在 if (shouldInsert >= 0) { result[i] = willBeSort; tmp.add(shouldInsert, willBeSort); continue; } shouldInsert = Math.abs(shouldInsert + 1); // 在最後位置插入 if (shouldInsert == tmp.size()) { result[i] = list.get(shouldInsert - 1); tmp.add(shouldInsert, willBeSort); continue; } // 在最前位置插入 if (shouldInsert == 0) { result[i] = list.get(0); tmp.add(shouldInsert, willBeSort); continue; } // 中間位置插入 int b = tmp.get(shouldInsert); int a = tmp.get(shouldInsert - 1); result[i] = Math.abs(a - willBeSort) > Math.abs(b - willBeSort) ? b : a; tmp.add(shouldInsert, willBeSort); } System.out.println(Joiner.on(",").join(result)); }
輸出結果:
0,1,8,6,6,6,5,1,1,8