Finding two non-subsequent elements in array which sum is minimal

前端 未结 13 1005
小蘑菇
小蘑菇 2021-02-05 03:40

Intro: As far as I could search, this question wasn\'t asked in SO yet.
This is an interview question.
I am not even specifically looking for a code sol

13条回答
  •  礼貌的吻别
    2021-02-05 04:07

    edit: you're right, I completely ignored the adjacency constraint. luckily I've thought of a solution. The algorithm goes like this:

    1. You run once over the array to find the smallest (O(n))
    2. You run a second time to find the second smallest (O(n))
    3. If second smallest is not adjacent to smallest we're done(O(1) - just an index check)
    4. Otherwise run a third time to find third smallest (still O(n))
    5. If not adjacent to smallest return smallest and third smallest otherwise return second and third smallest

提交回复
热议问题