zoukankan      html  css  js  c++  java
  • Google面试题

    今天早上在Quora上看到的一个题目,很不错的!最直观的是枚举n^3,但稍微进步一点的观察是找出3个数,然后最大的减去最小的2倍的结果,然后就有了线性扫一遍就OK。

    Given three arrays, A, B, and C, what is the best algorithm to find the minimum value of |a - b| + |b - c| + |c - a|, where  a in A, b in B, c in C?

    解答:

    Assuming that the arrays are not sorted, here is an nlogn algorithm.
    1. Sort the arrays A, B and C. Let there sizes be n,m and p.
    2. let i,j,k =0 points to the start indices of the 3 arrays.
    3. ans = INT_MAX;
    4. while(i < n && j<m && k<p)
              ans = min(ans, abs(A[i] - B[j]) + abs(B[j] - C[k]) + abs(C[k]-A[i]))
              increment the index of minumum of A[i], B[j], C[k]
    5. return ans;
    Sorting takes nlogn time. If the arrays are alread sorted, it would be an O(n) algo.

  • 相关阅读:
    ansible变量
    nginx连接php测试
    redis发布订阅
    堡垒机实例以及数据库操作
    nginx简介,使用
    protobuf
    go NSQ
    go mod
    GIT版本管理工具教程
    linux命令查询网站
  • 原文地址:https://www.cnblogs.com/sosi/p/3673009.html
Copyright © 2011-2022 走看看