二分查找-leetcode

/**
 * 
 * 278. First Bad Version
 * 
 * You are a product manager and currently leading a team to develop a new
 * product. Unfortunately, the latest version of your product fails the quality
 * check. Since each version is developed based on the previous version, all the
 * versions after a bad version are also bad.
 * 
 * Suppose you have n versions [1, 2, ..., n] and you want to find out the first
 * bad one, which causes all the following ones to be bad.
 * 
 * You are given an API bool isBadVersion(version) which will return whether
 * version is bad. Implement a function to find the first bad version. You
 * should minimize the number of calls to the API.
 * 
 * note: The isBadVersion API is defined in the parent class VersionControl.
 * boolean isBadVersion(int version);
 *
 */
public class Lc278 {
    /*
     * 本题利用二分查找,不同于普通的二分查找,本题是利用二分发找到最先出现的bad code,所以利用折半找到对应位置。
     * 
     * 需要注意的是常规的二分法是利用mid = (left+right)/2;如果left =
     * Integer.maxValue,right=Inter.maxValue,就会超过啦 可以用 left + (right-left) 就可以避免以上情况
     */
    public static int firstBadVersion(int n) {
        int left = 1;
        int right = n;
        while (right > left) {
            int mid = left + (right - left) / 2;
            if (isBadVersion(mid)) {
                right = mid;
            } else {
                left = left + 1;
            }
        }
        return left;
    }     public static boolean isBadVersion(int version) {
        return  false;
    }     public static void main(String[] args) {
        System.out.println(firstBadVersion(5));
    }
} /**
 * Given a sorted array and a target value, return the index if the target is
 * found. If not, return the index where it would be if it were inserted in
 * order.
 * 
 * You may assume no duplicates in the array.
 * 
 *
 */
public class Lc35 {
    /**
     *标准的二分查找题目
     *
     * 
     */
    public static int searchInsert(int[] nums, int target) {
        if (nums.length == 0) {
            return 0;
        }
        int left = 0;
        int right = nums.length;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                right = mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            }
        }
        return ++right;
    }     public static void main(String[] args) {
        int[] nums = { 1, 3 };
        int target = 2;
        System.out.println(searchInsert(nums, target));
    }
} import java.util.Arrays; /**
 * 
 * 33. Search in Rotated Sorted Array
 * 
 * Suppose an array sorted in ascending order is rotated at some pivot unknown
 * to you beforehand.
 * 
 * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
 * 
 * You are given a target value to search. If found in the array return its
 * index, otherwise return -1.
 * 
 * You may assume no duplicate exists in the array.
 * 
 * Your algorithm's runtime complexity must be in the order of O(log n).
 *
 */
public class Lc33 {
    /**
     * 数组之间相互指向是地址指向,值改变双方都是改变
     * 
     */
    public static int search(int[] nums, int target) {
        if (nums.length == 0) {
            return -1;
        }
        // 复制到新的空间
        int temp[] = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            temp[i] = nums[i];
        }
        // 排序
        Arrays.sort(temp);         int left = 0;
        int right = nums.length;         // 记录目标数据在排序后数组中的位置
        int position = Integer.MAX_VALUE;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (target == temp[mid]) {
                position = mid;
                break;
            } else if (temp[mid] > target) {
                right = mid;
            } else if (temp[mid] < target) {
                left = left + 1;
            }
        }
        // 数组中无该数据
        if (position == Integer.MAX_VALUE) {
            return -1;
        }
        // 找到目标数据在数组中的位置,找到对应值在原数组的位置
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == temp[position]) {
                return i;
            }
        }
        return nums.length;     }     public static void main(String[] args) {
        int nums[] = { 4, 5, 6, 7, 0, 1, 2 };
        int target = 0;
        System.out.println(search(nums, target));
    }
} /*
 * 
 * 153. Find Minimum in Rotated Sorted Array
 * 
 * 
 * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]). Find the minimum element. You may assume no duplicate exists in the array.
 */
public class Lc153 {
    /*
     * 首先对比俩端的数字,如果是左边小于右边,则无需比较,整体是升序;
     * 
     * 如果左边大于右边,如果中间位置的值大于左边,则中间值也在一组升序里面,则需让左边的边界为中间值 同理 右边也是
     */
    public static int findMin(int[] nums) {
        int left = 0;
        int right = nums.length;
        if (nums[left] < nums[right - 1]) {
            return nums[0];
        }         while (left < right - 2) {
            int mid = left + (right - left) / 2;
            if (nums[mid] > nums[left]) {
                left = mid;
            } else if (nums[mid] < nums[left]) {
                right = mid;
            }
        }
        return nums[right];
    }     public static void main(String[] args) {
        int[] nums = { 4, 5, 6, 7, 0, 1, 2 };
        System.out.println(findMin(nums));
    }
} /*
 * We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number is higher or lower. You call a pre-defined API guess(int num) which returns 3 possible results (-1, 1, or 0):
 */
public class Lc374 {
    /*
     * guess(int num)
     */
    public static int guessNumber(int n) {
        int left = 1;
        int right = n;
        while (left < right) {
            int mid = left + (right - left) / 2;
            int res = guess(mid);
            if (res == 0) {
                return mid;
            } else if (res == -1) {
                right = mid-1;
            } else if (res == 1) {
                left = mid+1;
            }
        }
        return n;
    }     private static int guess(int num) {
        if (num < 2) {
            return -1;
        }
        if (num > 2) {
            return 1;
        }
        return 0;
    }     public static void main(String[] args) {
        System.out.println(guessNumber(2));     }
}

二分查询-leetcode的更多相关文章

  1. C# 二分查询

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  2. 【洛谷P2894】Hotel 线段树+二分查询

    题目大意:给定一个长度为 N 的序列,每个点有两种状态 1/0,表示占有和空闲,现支持 first-fit 查询是否有一段连续的长度为 X 的空闲子序列和区间赋值操作. 题解:get到了线段树新技能. ...

  3. codeforces 633D - Fibonacci-ish 离散化 + 二分查询

    Fibonacci-ish Yash has recently learnt about the Fibonacci sequence and is very excited about it. He ...

  4. bzoj1257 数学整理二分查询

    2013-11-15 21:55 原题传送门http://www.lydsy.com/JudgeOnline/problem.php?id=1257 要求求sigma k mod i(i<=n) ...

  5. sql 中多表查询-leetcode : Combine Two Tables

    因为对数据库的内容早都忘得差不多了,所以我的第一感觉是: select Person.FirstName, Person.LastName, Address.City from Person, Add ...

  6. Light oj 1138 - Trailing Zeroes (III) (二分)

    题目链接:http://lightoj.com/volume_showproblem.php?problem=1138 题目就是给你一个数表示N!结果后面的0的个数,然后让你求出最小的N. 我们可以知 ...

  7. noip 2012 借教室 (线段树 二分)

    /* 维护区间最小值 数据不超int 相反如果long long的话会有一组数据超时 无视掉 ll int */ #include<iostream> #include<cstdio ...

  8. 编程内功修炼之数据结构—BTree(二)实现BTree插入、查询、删除操作

    1 package edu.algorithms.btree; import java.util.ArrayList; import java.util.List; /** * BTree类 * * ...

  9. 湖南省第十一届大学生程序设计竞赛:Internet of Lights and Switches(HASH+二分+异或前缀和)

    Internet of Lights and Switches Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 3  Solved: 3[Submit][ ...

随机推荐

  1. java程序员面试宝典之——Java 基础部分(1~10)

    基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语法,集合的语法,io 的语法,虚拟机方面的语法. 1.一个".java"源文件中是否可以包 ...

  2. 少用float浮动?

    在css中,float 属性定义元素在哪个方向浮动.也是我在css样式中常用到的属性,后来浏览了一些公司项目代码,发现float属性极少有人使用.随后做了一些调查和研究: 1.在ie6以下,float ...

  3. 【SSL1457】翻币问题

    题面: \[\Large\text{翻币问题}\] \[Time~Limit:1000MS~~Memory~Limit:65536K\] Description 有N个硬币(6<=N<=2 ...

  4. 使用Python开发小说下载器,不再为下载小说而发愁 #华为云·寻找黑马程序员#

    需求分析 免费的小说网比较多,我看的比较多的是笔趣阁.这个网站基本收费的章节刚更新,它就能同步更新,简直不要太叼.既然要批量下载小说,肯定要分析这个网站了- 在搜索栏输入地址后,发送post请求获取数 ...

  5. 关于软件定义IT基础设施的未来,深信服是这么思考的

    在今年的深信服创新大会上,软件定义IT基础设施成为非常重要的议题之一,深信服与2,000余位客户的CIO和合作伙伴一起围绕IT基础设施在数字化时代中的作用与价值进行了深入的探讨. 此外,深信服还联合I ...

  6. CollectionView常用的布局方式总结

    结合网上的collectionView常用布局整合的collectionView使用工具 下载地址 支持五种布局方式ZFCollectionViewLayoutType有两种ZFCollectionV ...

  7. Evevt Loop 事件循环

    目录 JavaScript 是一门单线程的语言 一.什么是event Loop的执行机制 练习 异步任务-setTimeout 练习1: 练习2: 练习3: 练习4: 二 事件队列作用 同步任务 例1 ...

  8. 洛谷 题解 P3385 【【模板】负环】

    一.声明 在下面的描述中,未说明的情况下,\(N\) 是顶点数,\(M\)是边数. 二.判负环算法盘点 想到判负环,我们会想到很多的判负环算法.例如: 1. Bellman-Ford 判负环 这个算法 ...

  9. 洛谷 题解 P1600 【天天爱跑步】 (NOIP2016)

    必须得说,这是一道难题(尤其对于我这样普及组205分的蒟蒻) 提交结果(NOIP2016 天天爱跑步): OJ名 编号 题目 状态 分数 总时间 内存 代码 / 答案文件 提交者 提交时间 Libre ...

  10. 统计学习方法与Python实现(二)——k近邻法

    统计学习方法与Python实现(二)——k近邻法 iwehdio的博客园:https://www.cnblogs.com/iwehdio/ 1.定义 k近邻法假设给定一个训练数据集,其中的实例类别已定 ...