2line C++ 8ms with explaination

  • -3
    class Solution {
        bool search(vector<int>& nums, int target) {
            for (int num:nums) if (num == target) return true;
            return false;

    With duplicates, binary search will also run in O(n), so why not simply check every element? What's the purpose of writing tens lines of code and getting the same complexity?

  • 1

    If the duplicates are very few, the binary search method can still get O(logN) time complexity which is important in practice.

  • 0

    When you have really huge data set and few duplicates, binary search can be much, much, much faster than linear search.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.