求一個數組中a[0...i-1] 離a[i]最接近的值_code趣事

來源:互聯網
上載者:User

部落客頁: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







 




聯繫我們

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