Given n numbers find minimum perimeter triangle

余生颓废 提交于 2020-01-30 02:34:34

问题


Encountered this problem in coding contest. Could think only O(n^2 log(n)) solution. I guess the expected was O(n log n).

I am given n numbers, I have to find 3 numbers that follow triangle inequality and have the smallest sum.

I hope this is quite easy to understand.

Eg. 10,2,5,1,8,20

Answer is 23 = (5+8+10)


回答1:


The longest side should be the successor of the second longest; otherwise, we could shrink the longest and thus the perimeter. Now you can use your binary search to find the third side over O(n) possibilities instead of O(n^2) (and actually, you don't even need to search if you iterate from small to large, though the sort will still cost you).




回答2:


I think the answer is something like this, assuming no duplicates in the numbers.

Sort the numbers. Then scan the numbers and take the first number that is smaller than the sum of the preceding two numbers. Call that x(n) . . . the nth position of the sorted series.

x(n) is one of the numbers, and so far we are O(n log(n)).

Then there are a limited number of previous choices. Then x(n-1) has to be one of the numbers, because x(n-2) + x(n-3) < x(n-1) < x(n). Then it is a simple scan up to x(n-1) to find the smallest number that matches. This could be at the beginning of the series, as in 2, 3, 8, 15, 16.

I think the analysis is essentially the same with duplicates.



来源:https://stackoverflow.com/questions/32388962/given-n-numbers-find-minimum-perimeter-triangle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!