Binary Search

Time complexity O(log(n)). When the question requires O(log(n)) time complexity, we always need to think whether it can be solved by binary search.

For binary search, there are several key elements to consider:

1. when to stop while loop?

2. how to change start pointer?

3. how to change end pointer?

4. is it required to find first/ last/ any position of target?

5. use iterative or recursive way, which is better?

According to template provide by Jiuzhang, we concludes a general way to implement binary sort.

 1 class Solution {
 2     /**
 3      * @param nums: The integer array.
 4      * @param target: Target to find.
 5      * @return: The first position of target. Position starts from 0.
 6      */
 7     public int binarySearch(int[] nums, int target) {
 8         if (nums == null || nums.length == 0) {
 9             return -1;
10         }
11
12         int start = 0, end = nums.length - 1;
13         while (start + 1 < end) {
14             int mid = start + (end - start) / 2;
15             if (nums[mid] == target) {
16                 end = mid;
17             } else if (nums[mid] < target) {
18                 start = mid;
19             } else {
20                 end = mid;
21             }
22         }
23         if (nums[start] == target) {
24             return start;
25         }
26         if (nums[end] == target) {
27             return end;
28         }
29         return -1;
30     }
31 }

From the template, we noticed that:

1. Each time, we set start = mid or end = mid to avoid index out of range.

2. Stop criterion is a. target is found b. start + 1 = end (i.e start and end are adjacent points).

In second situation, we need to check both start and end pointers.

If it‘s required to return first position --> first check start, then check end.

If it‘s required to return last position --> first check end, then check start.

时间: 2024-10-22 13:11:46

Binary Search的相关文章

[LeetCode] Find Mode in Binary Search Tree 找二分搜索数的众数

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than or equal to the nod

235. Lowest Common Ancestor of a Binary Search Tree

1. 问题描述 Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T th

leetcode 109 Convert Sorted List to Binary Search Tree

题目连接 https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ Convert Sorted List to Binary Search Tree Description Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. /** * De

Lowest Common Ancestor of a Binary Search Tree

1. Title 235. Lowest Common Ancestor of a Binary Search Tree 2. Http address https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ 3. The question Given a binary search tree (BST), find the lowest common ancestor (LCA) of two

LeetCode 50 Pow(x, n)(Math、Binary Search)(*)

翻译 实现pow(x, n). 原文 Implement pow(x, n). 分析 首先给大家推荐维基百科: zh.wikipedia.org/wiki/二元搜尋樹 en.wikipedia.org/wiki/Binary_search_tree 其次,大家也可以看看类似的一道题: LeetCode 69 Sqrt(x)(Math.Binary Search)(*) 然而这题我还是没有解出来,看看别人的解法-- class Solution { private: double myPowHel

LeetCode OJ :Unique Binary Search Trees II(唯一二叉搜索树)

题目如下所示:返回的结果是一个Node的Vector: Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example,Given n = 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2

[LeetCode]Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys

Binary Search Tree Iterator

QUESTION Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Note: next() and hasNext() should run in average O(1) time

LeetCode: Validata Binary Search Tree

LeetCode: Validata Binary Search Tree Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree o

LeetCode: Recover Binary Search Tree

LeetCode: Recover Binary Search Tree Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space s