资讯专栏INFORMATION COLUMN

[LeetCode] Binary Search [Beat 100%]

王陆宽 / 2191人阅读

摘要:的要点极简主义的参数名,不考虑溢出的中点初始化

Problem

Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists in nums and its index is 4

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: 2 does not exist in nums so return -1

Note:

You may assume that all elements in nums are unique.
n will be in the range [1, 10000].
The value of each element in nums will be in the range [-9999, 9999].

Beat 100%的要点:极简主义的参数名,不考虑溢出的中点初始化

Solution
class Solution {
    public int search(int[] nums, int target) {
        if (nums == null || nums.length == 0) return -1;
        int l = 0, r = nums.length-1;
        while (l <= r) {
            int m = (l+r)>>>1;
            if (nums[m] == target) return m;
            else if (nums[m] > target) r = m-1;
            else l = m+1;
        }
        return -1;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/77172.html

相关文章

  • Leetcode PHP题解--D33 700. Search in a Binary Search

    摘要:题目链接题目分析从给定的二叉树中,查找指定值及其子节点。思路这个好像不用多说什么了吧按先序遍历搜索,找到则返回。最终代码若觉得本文章对你有用,欢迎用爱发电资助。 700. Search in a Binary Search Tree 题目链接 700. Search in a Binary Search Tree 题目分析 从给定的二叉树中,查找指定值及其子节点。 思路 这个好像不用多...

    Blackjun 评论0 收藏0
  • [Leetcode] Validate Binary Search Tree 验证二叉搜索树

    摘要:注意这里的结构和不同的二叉树遍历一样,如果到空节点就返回,否则递归遍历左节点和右节点。唯一不同是加入了和,所以要在递归之前先判断是否符合和的条件。代码如果该节点大于上限返回假如果该节点小于下限返回假递归判断左子树和右子树 Validate Binary Search Tree Given a binary tree, determine if it is a valid binary...

    fuchenxuan 评论0 收藏0
  • leetcode98. Validate Binary Search Tree

    摘要:题目要求检验二叉查找树是否符合规则。二叉查找树是指当前节点左子树上的值均比其小,右子树上的值均比起大。因此在这里我们采用栈的方式实现中序遍历,通过研究中序遍历是否递增来判断二叉查找树是否符合规则。 题目要求 Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is...

    codercao 评论0 收藏0
  • leetcode98. Validate Binary Search Tree

    摘要:题目要求检验二叉查找树是否符合规则。二叉查找树是指当前节点左子树上的值均比其小,右子树上的值均比起大。因此在这里我们采用栈的方式实现中序遍历,通过研究中序遍历是否递增来判断二叉查找树是否符合规则。 题目要求 Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is...

    AlphaWatch 评论0 收藏0
  • leetcode98. Validate Binary Search Tree

    摘要:题目要求判断一个树是否是二叉查找树。二叉查找树即满足当前节点左子树的值均小于当前节点的值,右子树的值均大于当前节点的值。思路一可以看到,对二叉查找树的中序遍历结果应当是一个递增的数组。这里我们用堆栈的方式实现中序遍历。 题目要求 given a binary tree, determine if it is a valid binary search tree (BST). Assu...

    songze 评论0 收藏0

发表评论

0条评论

王陆宽

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<