Fastest way to search for an element in unsorted array

后端 未结 10 1767
北恋
北恋 2020-12-14 08:13

I just bumped on to this question today and was trying for a solution that is better than O(N) but could not come up with one.

Searched through SO but couldn\'t find

10条回答
  •  时光说笑
    2020-12-14 09:06

    This could be solved by using some tricks. In an unsorted array simly if we traverse through it, the complexity in worst case (when element is present at last index) would be O(N), where N is the size of array. So, here is the trick. First check the last index so that if the element is present at last index (the worst case) our code will be executed in O(1). and after that while the code to traverse and find the element. So, now the worst case complexity would be O(N-1).

    int findElement(int N, int arr[], int element){
      if(arr[N]==element){
        return i;
      }
      for(int i=0; i

提交回复
热议问题