Finding smallest value in an array most efficiently

后端 未结 13 1639
慢半拍i
慢半拍i 2020-11-29 07:02

There are N values in the array, and one of them is the smallest value. How can I find the smallest value most efficiently?

相关标签:
13条回答
  • 2020-11-29 07:59

    An O(1) sollution might be to just guess: The smallest number in your array will often be 0. 0 crops up everywhere. Given that you are only looking at unsigned numbers. But even then: 0 is good enough. Also, looking through all elements for the smallest number is a real pain. Why not just use 0? It could actually be the correct result!

    If the interviewer/your teacher doesn't like that answer, try 1, 2 or 3. They also end up being in most homework/interview-scenario numeric arrays...

    On a more serious side: How often will you need to perform this operation on the array? Because the sollutions above are all O(n). If you want to do that m times to a list you will be adding new elements to all the time, why not pay some time up front and create a heap? Then finding the smallest element can really be done in O(1), without resulting to cheating.

    0 讨论(0)
提交回复
热议问题