zoukankan      html  css  js  c++  java
  • *[topcoder]TaroFriends

    http://community.topcoder.com/stat?c=problem_statement&pm=13005

    好题。最暴力是试验2^n种跳法。然后有从结果入手,那么最终的左右是i, j,有n^2种(每种4个跳法),然后花O(n)的时间去验证。

    最后的正解比较有意思,就是观察到必须向里跳才有意义,那么只有RRRRRR...LLLLLL这种形式的才满足,于是遍历这个R和L的分界点就行了。

    #include <vector>
    #include <algorithm>
    #include <iostream>
    using namespace std;
    
    class TaroFriends {
    public:
        int getNumber(vector <int> coordinates, int X) {
            int ret = 1000000000;
            int N = coordinates.size();
            sort(coordinates.begin(), coordinates.end());
            for (int i = 0; i <= N; i++) {
                int minPos = 1000000000;
                int maxPos = -1000000000;
                for (int j = 0; j < N; j++) {
                    int pos = 0;
                    if (j < i) { // R
                        pos = coordinates[j] + X;
                    } else { // L
                        pos = coordinates[j] - X;
                    }
                    minPos = min(pos, minPos);
                    maxPos = max(pos, maxPos);
                }
                ret = min(ret, maxPos - minPos);
            }
            return ret;
        }
    };
    

      

  • 相关阅读:
    Gray Code
    Search a 2D Matrix
    Find Minimum in Rotated Sorted Array
    Feign理解
    Ribbon描述
    eureka自定义instance Id
    eureka开启用户认证
    idea创建Eureka consumer入门实例
    eureka描述
    activeMq的安全机制
  • 原文地址:https://www.cnblogs.com/lautsie/p/3899803.html
Copyright © 2011-2022 走看看