在阵列发现任何两个元素之间的最大的一笔距离阵列、元素、距离、两个

由网友(记得叫兽欧巴)分享简介:刚拿到这是面试的问题,并没有做太多热就可以了,我能得到它的工作缓慢而负数搞砸了。Just got this as job interview question and didn't do too hot on it, I was able to get it working slowly but negative n...

刚拿到这是面试的问题,并没有做太多热就可以了,我能得到它的工作缓慢而负数搞砸了。

Just got this as job interview question and didn't do too hot on it, I was able to get it working slowly but negative numbers screwed it up.

现在的问题是要找到每对包括减去指数之间的最大区别。所以它可能是更容易的例子来说明。

The question was to find the largest difference between each pair including subtracting the indices. so it might be easier to show with an example.

A = [1,-3,3];

答案是6,因为:

The answer would be 6 because:

a[2] + a[2] + (2-2) = 6

我没有我的解决方案,但我会尽量添加它,如果我能访问它。

I don't have my solution but I will try and add it in if I can get access to it.

他们正在寻找一个解决方案 O(N)

They were looking a solution in O(n).

推荐答案

我是pretty的确保正确的解决办法给你7不是6。

I am pretty sure the correct solution would give you 7 not 6.

a <- c(1,-3,3)

dist <- outer(a, a, FUN="-") + # matrix of first number minus second number
        outer(0:(length(a)-1), 0:(length(a)-1),"-") # adjust for diff in indices

max(dist) # returns 7

此距离是在3和-3(6)加上指数之间的差异(2-1或1-0 = 1,这取决于你语言),共7

This distance is between 3 and -3 (6) plus the difference between indices (2-1 or 1-0 =1, depending on your language) for a total of 7.

> outer(a, a, FUN="-") # note in r indices start with 1, but same idea
     [,1] [,2] [,3]
[1,]    0    4   -2
[2,]   -4    0   -6
[3,]    2    6    0
             ^this
> outer(0:(length(a)-1), 0:(length(a)-1),"-") 
     [,1] [,2] [,3]
[1,]    0   -1   -2
[2,]    1    0   -1
[3,]    2    1    0
             ^plus this
阅读全文

相关推荐

最新文章