码迷,mamicode.com
首页 > 编程语言 > 详细

求一个数组中a[0...i-1] 离a[i]最接近的值

时间:2014-12-04 08:50:36      阅读:342      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   sp   java   for   strong   

博客主页: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) {
                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;
            }

            if (willBeSort.equals(tmp.get(shouldInsert))) {
                result[i] = willBeSort;
                tmp.add(shouldInsert, willBeSort);
                continue;

            }

            int b = tmp.get(shouldInsert);
            int a = tmp.get(shouldInsert - 1);

            if (willBeSort.equals(a)) {
                result[i] = a;
                tmp.add(shouldInsert, willBeSort);
                continue;
            }

            if (willBeSort.equals(b)) {
                result[i] = b;
                tmp.add(shouldInsert, willBeSort);
                continue;

            }

            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







 




求一个数组中a[0...i-1] 离a[i]最接近的值

标签:style   blog   http   io   ar   sp   java   for   strong   

原文地址:http://blog.csdn.net/minna_d/article/details/41710389

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!