
Binary Search
文章平均质量分 59
再见小小ronnie
这个作者很懒,什么都没留下…
展开
-
Leetcode 34. Search for a Range
/** * Two binary search. * When isLeft is true search the left index of the target, * else search the right index of the index. */ public class Solution { public static int helper(int[] num原创 2017-01-03 10:33:06 · 225 阅读 · 0 评论 -
Leetcode 69. Sqrt(x)
public class Solution { public int mySqrt(int x) { long low = 0, high = x; while (low + 1 < high) { long mid = low + (high-low)/2; if (mid * mid > x)...原创 2017-01-26 12:23:43 · 149 阅读 · 0 评论 -
Leetcode 436. Find Right Interval
TreeMap is a Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys. The time complexity for containsKey, get, put and remove operations ar原创 2017-01-26 09:32:11 · 301 阅读 · 0 评论 -
Leetcode 441. Arranging Coins
Math. Solve the quadratic function k/2(k+1) k public class Solution { public int arrangeCoins(int n) { // math return (int) (-1+Math.sqrt(1+8*(double)n))/2; } }Binary searc原创 2017-01-22 10:41:16 · 181 阅读 · 0 评论 -
Leetcode 374. Guess Number Higher or Lower
Note that the param for guess() is the number you need to guess. e.g. guess(5) = 1 when the number you need to guess is 6. /** * We can easily figure out a O(n) solution which calls guess() from原创 2017-01-22 09:43:00 · 186 阅读 · 0 评论 -
Leetcode 278. First Bad Version
public class Solution extends VersionControl { public int firstBadVersion(int n) { int low = 1, high = n, mid = 0; while (low + 1 < high) { mid = low + (high - low) / 2原创 2017-01-22 09:18:45 · 167 阅读 · 0 评论 -
Leetcode 215. Kth Largest Element in an Array
/** * How quick sort works. * First choose a pivot, say the first element of the array, * set two pointer low and high point to the start and end of the array, * from high to low, find a element t原创 2017-01-22 05:54:57 · 178 阅读 · 0 评论 -
Leetcode 240. Search a 2D Matrix II
/** * Start from the top-right corner, check * if target > curr means we need to move to the next row b/c curr is the largest element in the row * if target < curr means we need to move to the prev原创 2017-01-22 03:23:55 · 162 阅读 · 0 评论 -
Leetcode 367. Valid Perfect Square
public class Solution { public boolean isPerfectSquare(int num) { long mid = 0; int low = 1, high = num; while (low <= high) { mid = (low+high)>>1;原创 2016-12-31 15:16:58 · 149 阅读 · 0 评论 -
Leetcode 35. Search Insert Position
public class Solution { public int searchInsert(int[] nums, int target) { int low = 0, high = nums.length-1, mid = 0; while (low <= high) { mid = (low+high) >> 1;原创 2017-01-03 13:04:21 · 170 阅读 · 0 评论 -
Leetcode 287. Find the Duplicate Number
/** * Pigenhold principle and binary search. * All integers are between [1, n], * choose mid as (1+n)/2, then count the number of integers that are <= mid in the array * if the number is greater t原创 2017-01-27 05:31:27 · 176 阅读 · 0 评论