lintcode 容易题:Binary Search

题目:

二分查找

给定一个排序的整数数组(升序)和一个要查找的整数target,用O(logn)的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1

样例

在数组 [1, 2, 3, 3, 4, 5, 10] 中二分查找3,返回2

挑战

如果数组中的整数个数超过了2^32,你的算法是否会出错?

解题:

利用二分查找,先判断左侧数据,满足条件则查找左侧,左侧不满足的时候在右侧找

当left>=right 时候表示没有找到返回 -1

当nums[left] ==target时候最左侧满足条件则找到了

再判断中位数是否满足条件

nums[median]==target and nums[median-1]!=target,return median

else:

对median的两侧进行判断

时间复杂度:O(logn)

Java程序:

class Solution {
    /**
     * @param nums: The integer array.
     * @param target: Target to find.
     * @return: The first position of target. Position starts from 0.
     */
    public int binarySearch(int[] nums, int target) {
        //write your code here
        if(nums.length==1 && nums[0]== target)
            return 0;
        int numsLen = nums.length;
        int index = binaryFind(nums,target,0,numsLen);
        return index;
    }
    public int binaryFind(int[] nums,int target,int left,int right){
        if(left>=right)
            return -1;
        if(nums[left]==target)
            return left;
        int median = (left+right)/2;
        if(target==nums[median] && target!=nums[median-1])
            return median;
        if(nums[median]>=target)
            return binaryFind(nums,target,left,median);
        else if(nums[median]<target)
            return binaryFind(nums,target,median+1,right);
        return -1;
    }
}

总耗时: 1504 ms

发现这里的运行时间,与我本地的网速关系很大。

直接线性查找,也是很简单的

    public int linFind(int[] nums ,int target){
        int numsLen = nums.length;
        for(int i=0;i<numsLen;i++)
            if(nums[i]==target)
                return i;
        return -1;
    }

总耗时: 1598 ms

耗时差不多的

当数组个数超过232 ,数组的下标是int型,已经越界,很大很大的时候median也会越界

Python程序:

class Solution:
    # @param nums: The integer array
    # @param target: Target number to find
    # @return the first position of target in nums, position start from 0
    def binarySearch(self, nums, target):
        # write your code here
        return self.linFind(nums,target)
        # return self.binaryFind(nums,target,0,len(nums))
    def linFind(self,nums,target):
        for i in range(len(nums)):
            if nums[i]==target:
                return i
        return -1

    def binaryFind(self,nums,target,left,right):
        if left>=right:
            return -1
        if nums[left]==target:
            return left
        median = (left+right)/2
        if nums[median]==target and nums[median-1]!=target:
            return median
        if nums[median]>=target:
            return self.binaryFind(nums,target,left,median)
        elif nums[median]<target:
            return self.binaryFind(nums,target,median+1,right)
        else:
            return -1

两个运行时间,也差不多的。

总耗时: 314 ms

总耗时: 303 ms

时间: 2024-12-11 17:19:13

lintcode 容易题:Binary Search的相关文章

[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree

95. Validate Binary Search Tree/98. Validate Binary Search Tree 本题难度: Easy Topic: Binary Tree Description 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 contain

LeetCode算法题-Binary Search(Java实现)

这是悦乐书的第297次更新,第316篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第165题(顺位题号是704).给定n个元素的排序(按升序)整数数组nums和目标值,编写一个函数来搜索nums中的目标.如果target存在,则返回其索引,否则返回-1.例如: 输入:nums = [-1,0,3,5,9,12],目标= 9 输出:4 说明:9存在于nums中,其索引为4 输入:nums = [-1,0,3,5,9,12],target = 2 输出:-1 说明:2在

lintcode 中等题:search a 2d matrix II 搜索二维矩阵II

题目 搜索二维矩阵 II 写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数. 这个矩阵具有以下特性: 每行中的整数从左到右是排序的. 每一列的整数从上到下是排序的. 在每一行或每一列中没有重复的整数. 样例 考虑下列矩阵: [     [1, 3, 5, 7],     [2, 4, 7, 8],     [3, 5, 9, 10] ] 给出target = 3,返回 2 挑战 要求O(m+n) 时间复杂度和O(1) 额外空间 解题 直接遍历,时间复杂度是O(MN) public

lintcode 容易题:Search a 2D Matrix 搜索二维矩阵

题目: 搜索二维矩阵 写出一个高效的算法来搜索 m × n矩阵中的值. 这个矩阵具有以下特性: 每行中的整数从左到右是排序的. 每行的第一个数大于上一行的最后一个整数. 样例 考虑下列矩阵: [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] 给出 target = 3,返回 true 挑战 O(log(n) + log(m)) 时间复杂度 解题: 1.最简单的方法就是遍历整个矩阵,时间复杂度:O(log(mn)),这个应该等于O(long(

lintcode 容易题:Insert Node in a Binary Search Tree 在二叉查找树中插入节点

题目:  在二叉查找树中插入节点 给定一棵二叉查找树和一个新的树节点,将节点插入到树中. 你需要保证该树仍然是一棵二叉查找树.  样例 给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的: 挑战 能否不使用递归? 解题: 递归的方法比较简单 Java程序: /** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public

[LintCode] Remove Node in Binary Search Tree

Remove Node in Binary Search Tree Given a root of Binary Search Tree with unique value for each node.  Remove the node with given value. If there is no such a node with given value in the binary search tree, do nothing. You should keep the tree still

[Lintcode] Validate Binary Search Tree

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 c

【Lintcode】087.Remove Node in Binary Search Tree

题目: Given a root of Binary Search Tree with unique value for each node. Remove the node with given value. If there is no such a node with given value in the binary search tree, do nothing. You should keep the tree still a binary search tree after rem

【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

[Lintcode] Insert Node in a Binary Search Tree

Insert Node in a Binary Search Tree Given a binary search tree and a new tree node, insert the node into the tree. You should keep the tree still be a valid binary search tree. Example Given binary search tree as follow, after Insert node 6, the tree