背景:题目不难,但由于是第一次用二分法写代码,在结束条件那个地方纠结了半天。
思路:简单二分法。
学习:二分法:当数据量很大适宜采用该方法。采用二分法查找时,数据需是排好序的。主要思想是:(设查找的数组区间为array[low, high])(1)确定该期间的中间位置K(2)将查找的值T与array[k]比较。若相等,查找成功返回此位置;否则确定新的查找区域,继续二分查找。区域确定如下:a.a...
分类:
其他好文 时间:
2015-02-09 16:09:48
阅读次数:
168
二分查找可以说是在经典不过的查找算法了,比如JAVA的库函数里,就有相应的代码实例。如下写出两个版本的二分查找,非递归和递归的
非递归的
public int binarySearch1(int[] a, int key) {
int low = 0;
int high = a.length-1;
int mid;
while (low <= high) {
mid = ...
分类:
其他好文 时间:
2015-02-06 18:55:18
阅读次数:
163
游戏里经常用的概率算法,比如随机一个数,看它落在哪段。
这里涉及到随机数之后,看如何查找落在哪个段,可以用二分查找来优化:
#include
using namespace std;
int binary_search_nearest(int* arr, int begin, int end, int val){
if (!arr){
return -1;
}
int mi...
分类:
其他好文 时间:
2015-02-06 13:18:06
阅读次数:
149
【题目】
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.The first integ...
分类:
其他好文 时间:
2015-02-04 16:43:23
阅读次数:
124
题目:
Suppose a sorted array 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.
The array may contain duplicate...
分类:
编程语言 时间:
2015-02-04 16:39:32
阅读次数:
150
题目:与33题类似,也是在被翻转的有序数组中查找元素。不同的是数组中可能有重复的元素出现。
分析:数组中的元素可以重复导致的问题就是如果first小于等于mid,那么前半部分也不一定是有序的,例如[1 3 1 1 1 1 1 ]。因此我们把判断条件进一步细分,分为三种情况,大于,小于和等于。等于的时候直接first++就可以了。
代码:class Solution {
public:
...
分类:
其他好文 时间:
2015-02-04 13:08:15
阅读次数:
148
/**
*Search_Seq($arr,$elem):顺序查找
*Search_Seq2($arr,$elem):顺序查找(优化)
*Search_bin($arr,$elem):二分查找
*SearchBST($elem):二叉搜索
*/
classSearch{
public$arr;
function__construct($arr)
{
$this->arr=$arr;
}
/**
*顺序查找
*@param$arr在$arr数组中查..
分类:
Web程序 时间:
2015-02-03 07:14:05
阅读次数:
168
Problem F
Solve It
Input: standard input
Output: standard output
Time Limit: 1 second
Memory Limit: 32 MB
Solve the equation:
p*e-x+ q*sin(x) + r*cos(x) + s*tan(x) + t*x2 + u = 0
...
分类:
其他好文 时间:
2015-02-02 18:17:29
阅读次数:
151
Problem D
Closest Sums
Input: standard input
Output: standard output
Time Limit: 3 seconds
Given is a set of integers and then a sequence of queries. A query gives you a number and asks to fin...
分类:
其他好文 时间:
2015-02-02 18:15:34
阅读次数:
168
二分查找二分查找算法基本思想二分查找算法的前置条件是,一个已经排序好的序列(在本篇文章中为了说明问题的方便,假设这个序列是升序排列的),这样在查找所要查找的元素时,首先与序列中间的元素进行比较,如果大于这个元素,就在当前序列的后半部分继续查找,如果小于这个元素,就在当前序列的前半部分继续查找,直到找...
分类:
其他好文 时间:
2015-02-02 12:13:14
阅读次数:
153