几天前有人给了Codility上的三个算法,本人向来脑子不灵光,加上这么多年没弄过算法了,感觉有些吃力。这些算法的solution自知很不成熟,希望抛砖引玉,多提意见。另外为避免翻译不当,令大家会错了意,故将原文贴出。

  1. You want to park your bicycle in a bicycle parking area where bike racks are aligned in a row. There are already N bikes parked there(each bike is attached to exactly one rack, but a rack can have multiple bikes attached to it). We call racks that already have bikes attached used.
     You want to park your bike in a rack in the parking area according to the following criteria:
            the chosen rack must lie between te first and the last used racks(inclusive);
            the distance between the chose rack and any other used rack is as big as possible.
    A description of the bikes already parked in the racks is given in a non-empty zero-indexed array A: element A[K] denotes the postion of the rack to which bike number K is attaced (for 0 <= K < N). The central position in the parking area is position 0. A positive value means that the rack is located A[K] meters to the right of the cetral position 0; a negative value means that it's located |A[K]| meters to the left.
    That, given a non-empty zero-indexed array A of N integers, returns the largest possible distance in meters between the chosen rack and any other used rack.
    Assume that:
            N is an integer within the range [2..100,000];
            each element of array A is an integer within the range [-1,000,000,000..1,000,000,000].
    Complexity:
            expected worst-case time complexity isO(N*log(N));
            expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).


    思考: 我觉得题目主要是篇阅读理解,实际上就是要寻求两点的最大距离,然后将车子停在这两点最中间的位置

     

  2. public int solution(int[] A) {
        Arrays.sort(A);
        int ans = Integer.MIN_VALUE;
        if (A.length == 2) return (A[1] - A[0]) / 2;
        for (int i=0; i < A.length - 1; i++) {
            //如果两点之间有空位置
            if (A[i+1] - A[i] > 1) {
                ans = Math.max(ans, A[i+1] - A[i]);
            }
        }
            
        return ans / 2;
    }