[关闭]
@Sarah 2016-01-30T06:06:15.000000Z 字数 1309 阅读 915

leet binary search

leetcode

  1. Search Insert Position My Submissions Question
    Total Accepted: 91279 Total Submissions: 249084 Difficulty: Medium
    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.
    Here are few examples.
    [1,3,5,6], 5 → 2
    [1,3,5,6], 2 → 1
    [1,3,5,6], 7 → 4
    [1,3,5,6], 0 → 0
  1. public int searchInsert(int[] A, int target) {
  2. int low = 0, high = A.length-1;
  3. while(low<=high){
  4. int mid = (low+high)/2;
  5. if(A[mid] == target) return mid;
  6. else if(A[mid] > target) high = mid-1;
  7. else low = mid+1;
  8. }
  9. return low;
  10. }

2

Search a 2D Matrix
15:00
Start
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 integer of each row is greater than the last integer of the previous row.
Have you met this question in a real interview? Yes
Example
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
Challenge
O(log(n) + log(m)) time

  1. public boolean searchMatrix(int[][] matrix, int target) {
  2. int row_num = matrix.length;
  3. int col_num = matrix[0].length;
  4. int begin = 0, end = row_num * col_num - 1;
  5. while(begin <= end){
  6. int mid = (begin + end) / 2;
  7. int mid_value = matrix[mid/col_num][mid%col_num];
  8. if( mid_value == target){
  9. return true;
  10. }else if(mid_value < target){
  11. //Should move a bit further, otherwise dead loop.
  12. begin = mid+1;
  13. }else{
  14. end = mid-1;
  15. }
  16. }
  17. return false;
  18. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注